SlideShare une entreprise Scribd logo
1  sur  57
Admin
Scripting as a Second Language
  Rob Dunn
  October 20th, 2011
Who the heck is this guy?
…seen a VBScript (or other) before and have used
  one in your network
  …downloaded one from the Spiceworks Script
  Center
  …dabbled in VBScripting but don’t know where to
  go next
  …wanted to get a little more from your current
  scripting skills


Assumptions
•   Anatomy of a VBScript (5 major elements)
  •   Error Handling
  •   Copying, Reading from, Writing to a file
  •   Reading command-line results
  •   Getting WMI and Active Directory Information
  •   Building a GUI for your scripts



Recipe for a great script
“Do you ever find yourself typing the same set of
commands over and over to get a certain task done?
Do you ever find yourself clicking the same set of
buttons in the same sequence in the same wizard just
to complete some chore - and then have to repeat the
same process for, say, multiple computers or multiple
user accounts?”
•   Create or change user/computer accounts
  •   Reset passwords
  •   Upload or download files via FTP
  •   Temp file/folder cleanups
  •   Execute SQL backups
  •   Get information about user/computer objects
  •   Watch print queues
  •   Email a user
  •   Install software
  •   .etc


Scripting. Why?
…allow for error handling
  …know how to debug
  …comment/document code
  …declare variables (best practice)
  …make your scripts as scaleable and generic as
  possible
  …be able to “Frankenscript”TM




  Remember, there are lots of ways of doing the
  same thing with code. Do what makes sense to you

Admin Scripting Skills
• VBScript requires no additional software to be
    installed on older servers and workstations.
  • VBScript is a runtime scripting language
    loosely based off of VBA and VB
  • You can build a GUI for your VBScripts using
    HTA (Javascripts too)
  • VBScript runs with less overhead, but it is not
    as powerful or intuitive as PowerShell

Why VBScript?
• Variables – a “container” where you can store values
    temporarily
  • Constant – a variable used like an alias (non-changing value)
  • Objects – a subset of predefined code which can allow access
    to system level functions. You can use a variable to reference
    an object by using ‘Set’
      – Properties – read/writable attributes of a particular object
      – Methods – actions that can be performed with an object
  • Functions – reusable code that can return a value via the
    calling command
  • Subroutines – reusable code that can be executed to perform
    a special task

  VBScripts run as a .vbs or .vbe file                http://goo.gl/KJ5op


Anatomy
There are two .exe’s which can run as the
scripting host:
• Wscript.exe: outputs messages to separate windows as
  messages occur.
• Cscript.exe: outputs messages to the command-line
  interface in succession.

Depending on how you are implementing your scripts, you
may choose to run one instead of the other.

Example: cscript.exe demo.vbs
Any time you wish to work with files, environment variables, Active
  Object method and property
     Directory, WMI, the Windows Shell, etc. you will need to “create” the
     corresponding object in your code.

  Dim objFSO, objFIle
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  Set objFile = objFSO.GetFile(“c:windowswindowsupdate.log”)
  wscript.echo objFile.DateLastModified

  Demo




Anatomy
Variable/Constant a permanent valuesrepopulated during
    Variables are temporarywith
    Constants are variables containers that may be which cannot be reset
    script execution with different values.
    programmatically.


  Dim strDescription
  strDescription = “testing 1, 2, 3."
  Const SpiceworldDescription = “awesome”
  strDescription = “I think Spiceworld is hella ” _
   & SpiceworldDescription
  wscript.echo strDescription
  Wscript.echo “That was “ & SpiceworldDescription

  Demo



Anatomy
Functions are used for returning values back directly to the code which
  Function
  called them.
                                         Here, we are passing a variable to a
  Dim strFileName                        function (a file path)…

  wscript.echo funGetLastModified(“c:windowswindowsupdate.log”)

  Function funGetLastModified(strFilename)
     Dim objFSO, objFIle
     Set objFSO = CreateObject("Scripting.FileSystemObject")
     Set objFile = objFSO.GetFile(strFilename)
     funGetLastModified = objFile.DateLastModified      …which is returned back
  End function                                          to wscript.echo here.

  Demo




Anatomy
Subroutine
  Dim strFileDate
  Call subGetLastModified(“c:windowswindowsupdate.log”)
  wscript.echo strFileDate

  Sub subGetLastModifed(strFilename)
     Dim objFSO, objFIle
     Set objFSO = CreateObject("Scripting.FileSystemObject")
     Set objFile = objFSO.GetFile(strFilename)
     strFileDate = objFile.DateLastModified
  End Sub

  Demo

  Subroutines are well suited for self-contained processes that don’t need to return values back to the
  originating code. Use it to work with items, files, etc. that remain somewhat independent from the
  rest of the script, such as displaying error messages.




Anatomy
•   Typos/fat-fingering
•   Invalid use of variable data
•   Syntax problems
•   Logic problems
•   Etc.

How do we get around these problems?
• You should always expect your scripts to encounter
  errors
• Anything encountered which isn’t expected is
  considered an “error” to the scripting engine
• In these cases, you’ll want to force the script to
  resume past errors and continue onward.

Use:
On Error Resume Next
Option Explicit
  Dim Scott, objPerson
  Dim Scott, objPerson
  Set objPerson = CreateObject(“Scripting.PersonObject")
  Set Scott = objPerson.MindControl(“Scott Brosnan")
      objPerson = CreateObject(“Scripting.PersonObject")
  On error resume next
  Set Scott
  Scott.walk=“through door”
              objPerson.MindControl(“Scott Brosnan")
  Scott.sing “Star Spangled Banner.wav”
  Scott.walk “through front door”
  Scott.echo “All done!”
  Scott.sing “Star Spangled Banner.wav”
  Scott.echo “All done!”




Mind control
Option Explicit
dim objFSO
set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.CopyFile "c:temptest.txt", "c:temptemp1"
MsgBox "Script finished."




If “test.txt” doesn’t exist on the computer running this script, the scripting host will produce
an error and terminate.
Now that your script can make it past its first error…

Let’s use this to our advantage by utilizing the ‘err’ object. It has a couple important
properties:

Err.number = provides numerical error
Err.description = sometimes provides more descriptive detail about error

On error resume next
„other code goes here
If err.number <> 0 then
   Msgbox err.number & “ – “ & err.description
End If
Reading from a text file via vbscript
goes a bit like this:

1. Use the filesystem object to open a text file
2. Either read the entire contents of the file into a
   variable, or move through each line to process
   that line individually
3. Call a function or subroutine to do something
   with the information in that variable
Option Explicit
Const ForReading = 1
Dim objFSO, sourcefile

Set objFSO = CreateObject("Scripting.FileSystemObject")
On error resume next
Set sourcefile = objFSO.OpenTextFile("c:tempcomputers.txt",ForReading)

Do Until sourcefile.AtEndOfStream = True
          wscript.echo sourcefile.readline
Loop

Set objFSO = nothing


      In order to read from a text file, we need to state that we are going to
      use a constant and the filesystem object.

      Next, we are going to open the file using the filesystem object (known
      as objFSO) by using the ‘OpenTextFile’ method.

      If we are going to process each line, we will need to tell the script how
      to handle it until the file reaches the end (using the AtEndOfStream
      method).
Option Explicit
Const ForWriting = 2
Dim objFSO, logfile

Set objFSO = CreateObject("Scripting.FileSystemObject")
On error resume next
Set Logfile = objFSO.OpenTextFile("c:templogfile.log", ForWriting, True)

Logfile.writeline("This is an entry in my logfile")

Logfile.close
Set objFSO = nothing


      In order to write to a text file, we need to specify we are going to use
      a constant and the filesystem object. Note the ‘ForWriting’ constant
      (instead of ‘ForReading’).

      Again, we are going to open the file using the filesystem object
      (known as objFSO) and use the ‘OpenTextFile’ method.

      The FileSystemobject grants us a ‘writeline’ method, enabling you to
      write text directly to a file.
Option Explicit
Dim WshShell, objExecResults

Set WshShell = CreateObject("WScript.Shell")
Set objExecResults = WshShell.Exec("ping.exe 127.0.0.1")

wscript.echo objExecResults.StdOut.ReadAll




      To read the output of a command line, we need to invoke the
      ‘wscript.shell’ object. This object allows us to execute a program
      using the ‘exec’ method.

      We are going to place the output of the execute method into
      ‘objExecResults.’

      In order to see our output in a readable format, we’ll use the ‘ReadAll’
      method to read the contents of objExecResults into a variable or
      directly to the screen.
Methods                                      Properties
   • AppActivate                                • CurrentDirectory
   • CreateShortcut                             • Environment
   • Exec
   • ExpandEnvironmentStrings                   • SpecialFolders
   • LogEvent
   • Popup
   • RegDelete
   • RegRead
   • RegWrite
   • Run
   • SendKeys


  Get sample usage and more details here: http://goo.gl/Rc3Z8

Wscript properties/methods
Methods                                      Properties
   • MapNetworkDrive                            • ComputerName
   • EnumNetworkDrives                          • UserDomain
   • RemoveNetworkDrive
   • AddPrinterConnection                       • UserName
   • AddWindowsPrinterConnection
   • EnumPrinterConnections
   • SetDefaultPrinter
   • RemovePrinterConnection




  Get sample usage and more details here: http://goo.gl/C9BT5

Wscript properties/methods
• WMI computer as the implementation of Web-based
Think of theis Microsoft’sdatabase, and the WMI classes at tables.
You Enterprise various WMI classes(WBEM) querying a SQL
    will query the Management as if you were
• Every
database modern Windows computer has a localized
  WMI repository
• Spiceworks gets a lot of its data from the WMI
  repository
• WMI class examples:
  Win32_logicaldisk, Win32_bios, Win32_Computer
  System
• You can quickly query local or remote repositories
  with VBScript, Powershell or Batch (etc.) scripts
To figure out how to query WMI via
VBScript (or other languages), you’ll need:
• Microsoft Scriptomatic 2.0
-or-
• WMIGen by Rob van der Woude

           These are tools which can allow you
           to generate specific code to import
           into your own scripts.
Microsoft Scriptomatic 2.0
WMIGen 7.03
Option Explicit
Dim objWMIService, strComputer, colItems
strComputer = "."

Set objWMIService = GetObject("winmgmts:" & strComputer & "rootCIMV2")
On error resume next
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_OperatingSystem", "WQL")

For Each objItem In colItems
           WScript.Echo "BootDevice: " & objItem.BootDevice
           WScript.Echo "Caption: " & objItem.Caption
           WScript.Echo "Service Pack: " & objItem.ServicePackMajorVersion
Next


      Instead of creating an object, we are getting an object, since this is
      already active. In this case, we are getting an object from the
      rootCIMV2 namespace…

      Next we are going to place the results of a WQL query into the
      colItems (collection) object.

      This particular script will return the local or remote computer’s boot
      device, OS name and service pack level.
Option Explicit
Dim objWMIService, strComputer, colItems
strComputer = "."

Set objWMIService = GetObject("winmgmts:" & strComputer & "rootCIMV2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_DiskDrive", "WQL")

For Each objItem In colItems
           WScript.Echo "Caption: " & objItem.Caption
           Wscript.echo "Size: " & objItem.Size
Next


      Here, we are querying the Win32_DiskDrive class…

      Since the results are placed into a collection (colItems), then we must
      loop through it, even if there might be only one item in the collection.
Option Explicit
Dim strComputer, objWMIService, colItems, strIPAddress

strComputer = "."
Set objWMIService = GetObject("winmgmts:" & strComputer & "rootCIMV2")
on error resume next

Set colItems = objWMIService.ExecQuery("SELECT * FROM
Win32_NetworkAdapterConfiguration", "WQL")

For Each objItem In colItems
  WScript.Echo "Description: " & objItem.Description
  strIPAddress = Join(objItem.IPAddress, ",")
  WScript.Echo "IPAddress: " & strIPAddress
Next


     Notice the ‘Join’ function. Some adapters have more than one IP
     address.
• Active Directory is a database of fields and
  values, think of a user/computer object as a
  record
• When querying AD, you should utilize filters to
  make your query more efficient
• You need to specify the attributes you wish to
  report against
  (pwdLastset, samAccountName,DN)
• You should try to isolate your queries to the OU
  structure where your results are located
Tools you will need

• Get AD Object Attributes VBScript http://goo.gl/csLFD
• ADExplorer (SysInternals) – find your attributes
• ADUC MMC – build your filter
The strFilter variable allows you to build your Active Directory filter. You
  The strAttributes variable should be populated with the fields you would
can use the Microsoft ADUC to build this query and paste into this
  like the script to report back. Things like user name, computer
variable.
  name, account creation date, etc. can be returned…
There are MANY ways to get
Active Directory data from
your network.

Do what works for you…
• HTA (HyperText Application) is
  essentially a web page with full system
  privileges - think of HTML + VBScript
• If you can write HTML, you can make an
  HTA
• Great for single-task functions (reset a
  password)
<html>
<head>
<title>HTA Helpomatic</title>

<HTA:APPLICATION
     ID="objHTAHelpomatic"
     APPLICATIONNAME="HTAHelpomatic"
     SCROLL="yes"
     SINGLEINSTANCE="yes"
     WINDOWSTATE="maximize"
>
</head>

<SCRIPT Language="VBScript">
</SCRIPT>
<body>Well, this is boring, huh?</body>
</html>
<input type=“text” name=“filetocheck” id=“txtfiletocheck”>
<button type=“button” name=“check” id=“btnCheck” onclick=“funGetLastModified(txtfiletocheck.value)”>
<input type=“text” name=“computername” id=“txtComputer”>
<button type=“button” name=“ping” id=“btnPing” onclick=“ping(txtComputername.value)”>
Tool                              Link (Case-sensitive)
Microsoft Scriptomatic v2.0       http://goo.gl/eL98u
Microsoft HTA-Helpomatic          http://goo.gl/cCvDM
Rob van der Woude’s WMIGen        http://goo.gl/jBNkv
PSPad Editor                      http://www.pspad.com
Notepad++ Editor                  http://notepad-plus-plus.org/
SysInternals’ ADExplorer          http://goo.gl/hzX48

Resource                          Link (Case-sensitive)
Microsoft VBScript reference      http://goo.gl/uDiFd
WScript Host object reference     http://goo.gl/uJHWn
Get AD Object Attributes Script   http://goo.gl/csLFD
Microsoft Script Center           http://goo.gl/9BcyD
All built-in VBScript Functions   http://goo.gl/iXza8
Scripting as a Second Language

Contenu connexe

Tendances

Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node jsfakedarren
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To ClosureRobert Nyman
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScriptTodd Anglin
 
Web Crawling with NodeJS
Web Crawling with NodeJSWeb Crawling with NodeJS
Web Crawling with NodeJSSylvain Zimmer
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tourcacois
 
Node js presentation
Node js presentationNode js presentation
Node js presentationmartincabrera
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleTom Croucher
 
CoffeeScript - An Introduction
CoffeeScript - An IntroductionCoffeeScript - An Introduction
CoffeeScript - An IntroductionManvendra Singh
 
Understanding GORM (Greach 2014)
Understanding GORM (Greach 2014)Understanding GORM (Greach 2014)
Understanding GORM (Greach 2014)Alonso Torres
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module PatternsNicholas Jansma
 

Tendances (20)

Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node js
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
Node.js
Node.jsNode.js
Node.js
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
SVN essentials
SVN essentialsSVN essentials
SVN essentials
 
Web Crawling with NodeJS
Web Crawling with NodeJSWeb Crawling with NodeJS
Web Crawling with NodeJS
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
 
Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tour
 
Tornadoweb
TornadowebTornadoweb
Tornadoweb
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
 
CoffeeScript - An Introduction
CoffeeScript - An IntroductionCoffeeScript - An Introduction
CoffeeScript - An Introduction
 
Understanding GORM (Greach 2014)
Understanding GORM (Greach 2014)Understanding GORM (Greach 2014)
Understanding GORM (Greach 2014)
 
Node ppt
Node pptNode ppt
Node ppt
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
JavaScript Looping Statements
JavaScript Looping StatementsJavaScript Looping Statements
JavaScript Looping Statements
 

Similaire à Scripting as a Second Language

Creative Web 2 - JavaScript
Creative Web 2 - JavaScript Creative Web 2 - JavaScript
Creative Web 2 - JavaScript Lukas Oppermann
 
XPages Blast - ILUG 2010
XPages Blast - ILUG 2010XPages Blast - ILUG 2010
XPages Blast - ILUG 2010Tim Clark
 
Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]srikanthbkm
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdfhamzadamani7
 
The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84Mahmoud Samir Fayed
 
Concurrency at the Database Layer
Concurrency at the Database Layer Concurrency at the Database Layer
Concurrency at the Database Layer mcwilson1
 
Modern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscanaModern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscanaMatteo Baglini
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipseanshunjain
 
Why Every Tester Should Learn Ruby
Why Every Tester Should Learn RubyWhy Every Tester Should Learn Ruby
Why Every Tester Should Learn RubyRaimonds Simanovskis
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...bobmcwhirter
 
Xopus Application Framework
Xopus Application FrameworkXopus Application Framework
Xopus Application FrameworkJady Yang
 

Similaire à Scripting as a Second Language (20)

Creative Web 2 - JavaScript
Creative Web 2 - JavaScript Creative Web 2 - JavaScript
Creative Web 2 - JavaScript
 
XPages Blast - ILUG 2010
XPages Blast - ILUG 2010XPages Blast - ILUG 2010
XPages Blast - ILUG 2010
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]
 
EnScript Workshop
EnScript WorkshopEnScript Workshop
EnScript Workshop
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
 
Javascript Workshop
Javascript WorkshopJavascript Workshop
Javascript Workshop
 
The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84
 
Concurrency at the Database Layer
Concurrency at the Database Layer Concurrency at the Database Layer
Concurrency at the Database Layer
 
React native
React nativeReact native
React native
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
Modern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscanaModern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscana
 
15. text files
15. text files15. text files
15. text files
 
Streams
StreamsStreams
Streams
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 
Why Every Tester Should Learn Ruby
Why Every Tester Should Learn RubyWhy Every Tester Should Learn Ruby
Why Every Tester Should Learn Ruby
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
 
Xopus Application Framework
Xopus Application FrameworkXopus Application Framework
Xopus Application Framework
 
All of Javascript
All of JavascriptAll of Javascript
All of Javascript
 

Dernier

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 

Dernier (20)

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

Scripting as a Second Language

  • 1. Admin Scripting as a Second Language Rob Dunn October 20th, 2011
  • 2. Who the heck is this guy?
  • 3. …seen a VBScript (or other) before and have used one in your network …downloaded one from the Spiceworks Script Center …dabbled in VBScripting but don’t know where to go next …wanted to get a little more from your current scripting skills Assumptions
  • 4. Anatomy of a VBScript (5 major elements) • Error Handling • Copying, Reading from, Writing to a file • Reading command-line results • Getting WMI and Active Directory Information • Building a GUI for your scripts Recipe for a great script
  • 5. “Do you ever find yourself typing the same set of commands over and over to get a certain task done? Do you ever find yourself clicking the same set of buttons in the same sequence in the same wizard just to complete some chore - and then have to repeat the same process for, say, multiple computers or multiple user accounts?”
  • 6. Create or change user/computer accounts • Reset passwords • Upload or download files via FTP • Temp file/folder cleanups • Execute SQL backups • Get information about user/computer objects • Watch print queues • Email a user • Install software • .etc Scripting. Why?
  • 7. …allow for error handling …know how to debug …comment/document code …declare variables (best practice) …make your scripts as scaleable and generic as possible …be able to “Frankenscript”TM Remember, there are lots of ways of doing the same thing with code. Do what makes sense to you Admin Scripting Skills
  • 8.
  • 9. • VBScript requires no additional software to be installed on older servers and workstations. • VBScript is a runtime scripting language loosely based off of VBA and VB • You can build a GUI for your VBScripts using HTA (Javascripts too) • VBScript runs with less overhead, but it is not as powerful or intuitive as PowerShell Why VBScript?
  • 10. • Variables – a “container” where you can store values temporarily • Constant – a variable used like an alias (non-changing value) • Objects – a subset of predefined code which can allow access to system level functions. You can use a variable to reference an object by using ‘Set’ – Properties – read/writable attributes of a particular object – Methods – actions that can be performed with an object • Functions – reusable code that can return a value via the calling command • Subroutines – reusable code that can be executed to perform a special task VBScripts run as a .vbs or .vbe file http://goo.gl/KJ5op Anatomy
  • 11. There are two .exe’s which can run as the scripting host: • Wscript.exe: outputs messages to separate windows as messages occur. • Cscript.exe: outputs messages to the command-line interface in succession. Depending on how you are implementing your scripts, you may choose to run one instead of the other. Example: cscript.exe demo.vbs
  • 12. Any time you wish to work with files, environment variables, Active Object method and property Directory, WMI, the Windows Shell, etc. you will need to “create” the corresponding object in your code. Dim objFSO, objFIle Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.GetFile(“c:windowswindowsupdate.log”) wscript.echo objFile.DateLastModified Demo Anatomy
  • 13. Variable/Constant a permanent valuesrepopulated during Variables are temporarywith Constants are variables containers that may be which cannot be reset script execution with different values. programmatically. Dim strDescription strDescription = “testing 1, 2, 3." Const SpiceworldDescription = “awesome” strDescription = “I think Spiceworld is hella ” _ & SpiceworldDescription wscript.echo strDescription Wscript.echo “That was “ & SpiceworldDescription Demo Anatomy
  • 14. Functions are used for returning values back directly to the code which Function called them. Here, we are passing a variable to a Dim strFileName function (a file path)… wscript.echo funGetLastModified(“c:windowswindowsupdate.log”) Function funGetLastModified(strFilename) Dim objFSO, objFIle Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.GetFile(strFilename) funGetLastModified = objFile.DateLastModified …which is returned back End function to wscript.echo here. Demo Anatomy
  • 15. Subroutine Dim strFileDate Call subGetLastModified(“c:windowswindowsupdate.log”) wscript.echo strFileDate Sub subGetLastModifed(strFilename) Dim objFSO, objFIle Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.GetFile(strFilename) strFileDate = objFile.DateLastModified End Sub Demo Subroutines are well suited for self-contained processes that don’t need to return values back to the originating code. Use it to work with items, files, etc. that remain somewhat independent from the rest of the script, such as displaying error messages. Anatomy
  • 16. Typos/fat-fingering • Invalid use of variable data • Syntax problems • Logic problems • Etc. How do we get around these problems?
  • 17.
  • 18. • You should always expect your scripts to encounter errors • Anything encountered which isn’t expected is considered an “error” to the scripting engine • In these cases, you’ll want to force the script to resume past errors and continue onward. Use: On Error Resume Next
  • 19. Option Explicit Dim Scott, objPerson Dim Scott, objPerson Set objPerson = CreateObject(“Scripting.PersonObject") Set Scott = objPerson.MindControl(“Scott Brosnan") objPerson = CreateObject(“Scripting.PersonObject") On error resume next Set Scott Scott.walk=“through door” objPerson.MindControl(“Scott Brosnan") Scott.sing “Star Spangled Banner.wav” Scott.walk “through front door” Scott.echo “All done!” Scott.sing “Star Spangled Banner.wav” Scott.echo “All done!” Mind control
  • 20.
  • 21.
  • 22. Option Explicit dim objFSO set objFSO = CreateObject("Scripting.FileSystemObject") objFSO.CopyFile "c:temptest.txt", "c:temptemp1" MsgBox "Script finished." If “test.txt” doesn’t exist on the computer running this script, the scripting host will produce an error and terminate.
  • 23. Now that your script can make it past its first error… Let’s use this to our advantage by utilizing the ‘err’ object. It has a couple important properties: Err.number = provides numerical error Err.description = sometimes provides more descriptive detail about error On error resume next „other code goes here If err.number <> 0 then Msgbox err.number & “ – “ & err.description End If
  • 24.
  • 25. Reading from a text file via vbscript goes a bit like this: 1. Use the filesystem object to open a text file 2. Either read the entire contents of the file into a variable, or move through each line to process that line individually 3. Call a function or subroutine to do something with the information in that variable
  • 26. Option Explicit Const ForReading = 1 Dim objFSO, sourcefile Set objFSO = CreateObject("Scripting.FileSystemObject") On error resume next Set sourcefile = objFSO.OpenTextFile("c:tempcomputers.txt",ForReading) Do Until sourcefile.AtEndOfStream = True wscript.echo sourcefile.readline Loop Set objFSO = nothing In order to read from a text file, we need to state that we are going to use a constant and the filesystem object. Next, we are going to open the file using the filesystem object (known as objFSO) by using the ‘OpenTextFile’ method. If we are going to process each line, we will need to tell the script how to handle it until the file reaches the end (using the AtEndOfStream method).
  • 27.
  • 28. Option Explicit Const ForWriting = 2 Dim objFSO, logfile Set objFSO = CreateObject("Scripting.FileSystemObject") On error resume next Set Logfile = objFSO.OpenTextFile("c:templogfile.log", ForWriting, True) Logfile.writeline("This is an entry in my logfile") Logfile.close Set objFSO = nothing In order to write to a text file, we need to specify we are going to use a constant and the filesystem object. Note the ‘ForWriting’ constant (instead of ‘ForReading’). Again, we are going to open the file using the filesystem object (known as objFSO) and use the ‘OpenTextFile’ method. The FileSystemobject grants us a ‘writeline’ method, enabling you to write text directly to a file.
  • 29.
  • 30. Option Explicit Dim WshShell, objExecResults Set WshShell = CreateObject("WScript.Shell") Set objExecResults = WshShell.Exec("ping.exe 127.0.0.1") wscript.echo objExecResults.StdOut.ReadAll To read the output of a command line, we need to invoke the ‘wscript.shell’ object. This object allows us to execute a program using the ‘exec’ method. We are going to place the output of the execute method into ‘objExecResults.’ In order to see our output in a readable format, we’ll use the ‘ReadAll’ method to read the contents of objExecResults into a variable or directly to the screen.
  • 31. Methods Properties • AppActivate • CurrentDirectory • CreateShortcut • Environment • Exec • ExpandEnvironmentStrings • SpecialFolders • LogEvent • Popup • RegDelete • RegRead • RegWrite • Run • SendKeys Get sample usage and more details here: http://goo.gl/Rc3Z8 Wscript properties/methods
  • 32. Methods Properties • MapNetworkDrive • ComputerName • EnumNetworkDrives • UserDomain • RemoveNetworkDrive • AddPrinterConnection • UserName • AddWindowsPrinterConnection • EnumPrinterConnections • SetDefaultPrinter • RemovePrinterConnection Get sample usage and more details here: http://goo.gl/C9BT5 Wscript properties/methods
  • 33.
  • 34. • WMI computer as the implementation of Web-based Think of theis Microsoft’sdatabase, and the WMI classes at tables. You Enterprise various WMI classes(WBEM) querying a SQL will query the Management as if you were • Every database modern Windows computer has a localized WMI repository • Spiceworks gets a lot of its data from the WMI repository • WMI class examples: Win32_logicaldisk, Win32_bios, Win32_Computer System • You can quickly query local or remote repositories with VBScript, Powershell or Batch (etc.) scripts
  • 35. To figure out how to query WMI via VBScript (or other languages), you’ll need: • Microsoft Scriptomatic 2.0 -or- • WMIGen by Rob van der Woude These are tools which can allow you to generate specific code to import into your own scripts.
  • 37.
  • 39.
  • 40. Option Explicit Dim objWMIService, strComputer, colItems strComputer = "." Set objWMIService = GetObject("winmgmts:" & strComputer & "rootCIMV2") On error resume next Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_OperatingSystem", "WQL") For Each objItem In colItems WScript.Echo "BootDevice: " & objItem.BootDevice WScript.Echo "Caption: " & objItem.Caption WScript.Echo "Service Pack: " & objItem.ServicePackMajorVersion Next Instead of creating an object, we are getting an object, since this is already active. In this case, we are getting an object from the rootCIMV2 namespace… Next we are going to place the results of a WQL query into the colItems (collection) object. This particular script will return the local or remote computer’s boot device, OS name and service pack level.
  • 41. Option Explicit Dim objWMIService, strComputer, colItems strComputer = "." Set objWMIService = GetObject("winmgmts:" & strComputer & "rootCIMV2") Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_DiskDrive", "WQL") For Each objItem In colItems WScript.Echo "Caption: " & objItem.Caption Wscript.echo "Size: " & objItem.Size Next Here, we are querying the Win32_DiskDrive class… Since the results are placed into a collection (colItems), then we must loop through it, even if there might be only one item in the collection.
  • 42. Option Explicit Dim strComputer, objWMIService, colItems, strIPAddress strComputer = "." Set objWMIService = GetObject("winmgmts:" & strComputer & "rootCIMV2") on error resume next Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration", "WQL") For Each objItem In colItems WScript.Echo "Description: " & objItem.Description strIPAddress = Join(objItem.IPAddress, ",") WScript.Echo "IPAddress: " & strIPAddress Next Notice the ‘Join’ function. Some adapters have more than one IP address.
  • 43.
  • 44. • Active Directory is a database of fields and values, think of a user/computer object as a record • When querying AD, you should utilize filters to make your query more efficient • You need to specify the attributes you wish to report against (pwdLastset, samAccountName,DN) • You should try to isolate your queries to the OU structure where your results are located
  • 45. Tools you will need • Get AD Object Attributes VBScript http://goo.gl/csLFD • ADExplorer (SysInternals) – find your attributes • ADUC MMC – build your filter
  • 46. The strFilter variable allows you to build your Active Directory filter. You The strAttributes variable should be populated with the fields you would can use the Microsoft ADUC to build this query and paste into this like the script to report back. Things like user name, computer variable. name, account creation date, etc. can be returned…
  • 47.
  • 48.
  • 49. There are MANY ways to get Active Directory data from your network. Do what works for you…
  • 50.
  • 51. • HTA (HyperText Application) is essentially a web page with full system privileges - think of HTML + VBScript • If you can write HTML, you can make an HTA • Great for single-task functions (reset a password)
  • 52. <html> <head> <title>HTA Helpomatic</title> <HTA:APPLICATION ID="objHTAHelpomatic" APPLICATIONNAME="HTAHelpomatic" SCROLL="yes" SINGLEINSTANCE="yes" WINDOWSTATE="maximize" > </head> <SCRIPT Language="VBScript"> </SCRIPT> <body>Well, this is boring, huh?</body> </html>
  • 53.
  • 54. <input type=“text” name=“filetocheck” id=“txtfiletocheck”> <button type=“button” name=“check” id=“btnCheck” onclick=“funGetLastModified(txtfiletocheck.value)”> <input type=“text” name=“computername” id=“txtComputer”> <button type=“button” name=“ping” id=“btnPing” onclick=“ping(txtComputername.value)”>
  • 55.
  • 56. Tool Link (Case-sensitive) Microsoft Scriptomatic v2.0 http://goo.gl/eL98u Microsoft HTA-Helpomatic http://goo.gl/cCvDM Rob van der Woude’s WMIGen http://goo.gl/jBNkv PSPad Editor http://www.pspad.com Notepad++ Editor http://notepad-plus-plus.org/ SysInternals’ ADExplorer http://goo.gl/hzX48 Resource Link (Case-sensitive) Microsoft VBScript reference http://goo.gl/uDiFd WScript Host object reference http://goo.gl/uJHWn Get AD Object Attributes Script http://goo.gl/csLFD Microsoft Script Center http://goo.gl/9BcyD All built-in VBScript Functions http://goo.gl/iXza8

Notes de l'éditeur

  1. This template can be used as a starter file for presenting training materials in a group setting.SectionsRight-click on a slide to add sections. Sections can help to organize your slides or facilitate collaboration between multiple authors.NotesUse the Notes section for delivery notes or to provide additional details for the audience. View these notes in Presentation View during your presentation. Keep in mind the font size (important for accessibility, visibility, videotaping, and online production)Coordinated colors Pay particular attention to the graphs, charts, and text boxes.Consider that attendees will print in black and white or grayscale. Run a test print to make sure your colors work when printed in pure black and white and grayscale.Graphics, tables, and graphsKeep it simple: If possible, use consistent, non-distracting styles and colors.Label all graphs and tables.
  2. I’m a network administrator who hates doing the same thing over and over again (if I can help it)In the trenches for about 17 yearsI’ve been using Spiceworks since 2007, I run a blog called “confessions of a freeware junkie” and did a review back when Spiceworks was just a baby at version 1.1I work for Rockford Orthopedic Associates, a premier orthopedic clinic in the Northern IL region, about 45 minutes away from ChicagoOur environment is made up of 380 workstations with 30 servers consisting of XP, 7, Server 2k3 and 2k8I’ve submitted 28 scripts to the Spiceworks community, some of them small, some of them pretty complex, but all helpful, or at least I hope!I don’t know everything about scripting
  3. In addition to all these things, you should have a good grasp on things like documenting and commenting on your code.The overall goal of this presentation is for you to take it with you and use it as a reference of sorts to go over some fundamental ways you can enhance or create your own administration scripts.-leader point: Let’s talk about the innards of a VBScript
  4. This is just a very short list of things you can do with scripting. You are really only limited by your scripting skills and your imagination.
  5. Declare variables: If you don’t declare the variables at the top of your scripts, any mistyped variables later on in the code will tell the scripting host to go ahead and create a new dynamic variable (even though it is misspelled). Using ‘Option Explicit’ will help you keep your variables in line. I can’t express to you how important it is to document your code. If you come back to it months or even years later, you’ll thank yourself for taking the time to put something in there that will save the future you a major headache!
  6. Exensible – you can use ActiveX(!) controls with VBScript.
  7. You should know about these 5 major elements within VBScript to build a decent administration script – there are more…Errors, Events, Keywords (Empty – determines if a variable is initialized, False which equals 0, Nothing – which releases an object from a variable, Null, True which equals 1) Operators (Arithmetic, Comparison – less than, equal than greater than or equal to, Concatenation, etc.)Statements (Do…Loop, Exit, Randomize, Select Case, On Error)CONSTANTS – these cannot be assigned dynamically. This improves the readability of your code.There are two kinds of functions – ones that you build for your specific purposes, and others like ‘msgbox’, ‘createobject’, ‘Time’, ‘Now’, ‘replace’ or ‘cstring’ that you can reference at any time without defining them.
  8. If you were running a script in a purely automated sense, i.e. a scheduled task, you may want to run it in the console, so a script won’t “hang” waiting for input if using the wscript engine.Since we are talking about scripts that hang, let’s discuss some error handling before we go too much further.
  9. The advantage to constants is that these values cannot be changed inadvertently throughout your code. Currency exchange rate would be a good example of a constant.VBScript has a number of built-in, or intrinsic constants, like for example, ‘vbSunday’ will always = 1, ‘vbCrLf’ will always = a carriage return-linefeed combination, vbTab will equal a horizontal tab.
  10. When you create a function within VBScript, the scripting host will automatically create and initialize a variable of the same name
  11. Give a brief overview of the presentation. Describe the major focus of the presentation and why it is important.Introduce each of the major topics.To provide a road map for the audience, you can repeat this Overview slide throughout the presentation, highlighting the particular topic you will discuss next.
  12. Story of Scott walking through a door and crashing into door when it isn’t open.
  13. On error resume next will not handle invalid code syntax. The Scripting engine evaluates the code prior to it running to see if it has a proper syntax.You might actually want to use a combination of on error resume next and on error goto 0. For example, you might have a bit of code that absolutely requires that it works before processing another section of code. Of course, if you have really good error handling built in here, you might not even need on error goto 0.
  14. We’re going to go through a simple copy script and see how error handling could help it, and then transition to a few useful tasks to make your scripts more useful, like reading from a file, writing to a file, and reading command-line results before we get into WMI and Active Directory database queries.
  15. Since we will experience an unhandled error (meaning we didn’t tell the script to resume past errors), we will never see the msgbox pop up as the script ended prematurely.Place “On error resume next” above the line of code you expect will run into troubles.
  16. Give a brief overview of the presentation. Describe the major focus of the presentation and why it is important.Introduce each of the major topics.To provide a road map for the audience, you can repeat this Overview slide throughout the presentation, highlighting the particular topic you will discuss next.
  17. Typically, you would insert the ‘on error resume next’ code snippet above the line that you expect will run into an error.
  18. Give a brief overview of the presentation. Describe the major focus of the presentation and why it is important.Introduce each of the major topics.To provide a road map for the audience, you can repeat this Overview slide throughout the presentation, highlighting the particular topic you will discuss next.
  19. Give a brief overview of the presentation. Describe the major focus of the presentation and why it is important.Introduce each of the major topics.To provide a road map for the audience, you can repeat this Overview slide throughout the presentation, highlighting the particular topic you will discuss next.
  20. You create a WshShell object whenever you want to run a program locally, manipulate the contents of the registry, create a shortcut, or access a system folder. The WshShellobject provides the Environment collection. This collection allows you to handle environmental variables (such as WINDIR, PATH, or PROMPT).
  21. You’ll need ADExplorer (or another LDAP browser) to take a first-hand look at the Active Directory objects so you know what you are looking for.You can use the ADUC MMC to find out how to build an AD filter.Going through the intricacies of how to to fully query AD from scratch is a bit out of scope for this session, but I will show you how you can use the script.Break out to show Object Attribute script.
  22. You’ll need ADExplorer (or another LDAP browser) to take a first-hand look at the Active Directory objects so you know what you are looking for.You can use the ADUC MMC to find out how to build an AD filter.Going through the intricacies of how to to fully query AD from scratch is a bit out of scope for this session, but I will show you how you can use the script.Rob van der Woude’s WMI gen is a little more thorough in that it can output WMI script code for 14 different languages.Break out to show Object Attribute script.
  23. You’ll need ADExplorer (or another LDAP browser) to take a first-hand look at the Active Directory objects so you know what you are looking for.You can use the ADUC MMC to find out how to build an AD filter.Going through the intricacies of how to to fully query AD from scratch is a bit out of scope for this session, but I will show you how you can use the script.Break out to show Object Attribute script.
  24. Notice the join function – this is where having a tool like Scriptomatic can come in very handy. Without the tool, you might be spending a lot of time looking up how to get each address instead of referring once to the application.
  25. You’ll need ADExplorer (or another LDAP browser) to take a first-hand look at the Active Directory objects so you know what you are looking for.You can use the ADUC MMC to find out how to build an AD filter.Going through the intricacies of how to to fully query AD from scratch is a bit out of scope for this session, but I will show you how you can use the script.Break out to show Object Attribute script.
  26. You’ll need ADExplorer (or another LDAP browser) to take a first-hand look at the Active Directory objects so you know what you are looking for.You can use the ADUC MMC to find out how to build an AD filter.Going through the intricacies of how to to fully query AD from scratch is a bit out of scope for this session, but I will show you how you can use the script.Break out to show Object Attribute script.
  27. Here is a snippet of the script that can pull
  28. Remember how I said you could use the ADUC MMC to help you with your filters? Here’s a way. If you can filter it in your ADUC, you can use those same filters in your AD Object attribute script!
  29. Here you can see the four main variables of the object attribute script that you may want to tweak (there are others, but these are not important to change now). Focus on the bottom two attributes. Here you can add filters to your AD query.
  30. Hyper-Text applications are rendered by IE, so if IE isn’t working, very likely, neither will your HTA’s. With that said, the Windows XP add/remove program is an HTA.HTA is a much better method of letting users enter parameters for scripts, rather than simple inputboxes.
  31. This will create a basic white page with no fields or elements contained within it. Note the &lt;script&gt; section. This is where you can place your custom script code. If you give your HTML elements ID’s, you can reference these with your code.
  32. I’ll show you quickly how we can build a very simple HTA using the script from before (get a file version)
  33. Give a brief overview of the presentation. Describe the major focus of the presentation and why it is important.Introduce each of the major topics.To provide a road map for the audience, you can repeat this Overview slide throughout the presentation, highlighting the particular topic you will discuss next.
  34. Give a brief overview of the presentation. Describe the major focus of the presentation and why it is important.Introduce each of the major topics.To provide a road map for the audience, you can repeat this Overview slide throughout the presentation, highlighting the particular topic you will discuss next.
  35. Give a brief overview of the presentation. Describe the major focus of the presentation and why it is important.Introduce each of the major topics.To provide a road map for the audience, you can repeat this Overview slide throughout the presentation, highlighting the particular topic you will discuss next.