This document provides an overview of scripting with VBScript, including the anatomy of a VBScript, error handling, reading from and writing to files, reading command line results, querying WMI and Active Directory, and building GUIs with HTA. It discusses variables, constants, objects, functions, and subroutines as the main elements of a VBScript. It also provides examples of reading from and writing to files, executing commands and reading the output, and querying WMI classes. Finally, it mentions tools like Microsoft Scriptomatic and WMIGen that can help generate VBScript code.
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.
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.
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)
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
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.
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
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
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.
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!
Exensible – you can use ActiveX(!) controls with VBScript.
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.
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.
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.
When you create a function within VBScript, the scripting host will automatically create and initialize a variable of the same name
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.
Story of Scott walking through a door and crashing into door when it isn’t open.
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.
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.
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.
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.
Typically, you would insert the ‘on error resume next’ code snippet above the line that you expect will run into an error.
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.
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.
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).
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.
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.
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.
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.
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.
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.
Here is a snippet of the script that can pull
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!
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.
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.
This will create a basic white page with no fields or elements contained within it. Note the <script> 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.
I’ll show you quickly how we can build a very simple HTA using the script from before (get a file version)
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.
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.
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.