Scripting as a Second Language

  • 1,221 views
Uploaded on

A presentation discussing the benefits of VBScripting in today's even with the advent of PowerShell. This presentation also discusses building an HTA for your VBScripts and accessing WMI and AD …

A presentation discussing the benefits of VBScripting in today's even with the advent of PowerShell. This presentation also discusses building an HTA for your VBScripts and accessing WMI and AD information.

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
  • I would recommend downloading this presentation and viewing it in PowerPoint (or the viewer). There are some animations, etc. that will be in the way of some information on the various slides... - Rob
    Are you sure you want to
    Your message goes here
No Downloads

Views

Total Views
1,221
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
38
Comments
1
Likes
2

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • 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.

Transcript

  • 1. AdminScripting 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 skillsAssumptions
  • 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 scriptsRecipe for a great script
  • 5. “Do you ever find yourself typing the same set ofcommands over and over to get a certain task done?Do you ever find yourself clicking the same set ofbuttons in the same sequence in the same wizard justto complete some chore - and then have to repeat thesame process for, say, multiple computers or multipleuser 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 • .etcScripting. 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 youAdmin Scripting Skills
  • 8. • 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 PowerShellWhy VBScript?
  • 9. • 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/KJ5opAnatomy
  • 10. There are two .exe’s which can run as thescripting 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, youmay choose to run one instead of the other.Example: cscript.exe demo.vbs
  • 11. 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 DemoAnatomy
  • 12. 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 DemoAnatomy
  • 13. 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. DemoAnatomy
  • 14. 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
  • 15. • Typos/fat-fingering• Invalid use of variable data• Syntax problems• Logic problems• Etc.How do we get around these problems?
  • 16. • 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
  • 17. 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
  • 18. Option Explicitdim objFSOset 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 producean error and terminate.
  • 19. 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 importantproperties:Err.number = provides numerical errorErr.description = sometimes provides more descriptive detail about errorOn error resume next„other code goes hereIf err.number <> 0 then Msgbox err.number & “ – “ & err.descriptionEnd If
  • 20. Reading from a text file via vbscriptgoes a bit like this:1. Use the filesystem object to open a text file2. Either read the entire contents of the file into a variable, or move through each line to process that line individually3. Call a function or subroutine to do something with the information in that variable
  • 21. Option ExplicitConst ForReading = 1Dim objFSO, sourcefileSet objFSO = CreateObject("Scripting.FileSystemObject")On error resume nextSet sourcefile = objFSO.OpenTextFile("c:tempcomputers.txt",ForReading)Do Until sourcefile.AtEndOfStream = True wscript.echo sourcefile.readlineLoopSet 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).
  • 22. Option ExplicitConst ForWriting = 2Dim objFSO, logfileSet objFSO = CreateObject("Scripting.FileSystemObject")On error resume nextSet Logfile = objFSO.OpenTextFile("c:templogfile.log", ForWriting, True)Logfile.writeline("This is an entry in my logfile")Logfile.closeSet 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.
  • 23. Option ExplicitDim WshShell, objExecResultsSet 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.
  • 24. 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/Rc3Z8Wscript properties/methods
  • 25. Methods Properties • MapNetworkDrive • ComputerName • EnumNetworkDrives • UserDomain • RemoveNetworkDrive • AddPrinterConnection • UserName • AddWindowsPrinterConnection • EnumPrinterConnections • SetDefaultPrinter • RemovePrinterConnection Get sample usage and more details here: http://goo.gl/C9BT5Wscript properties/methods
  • 26. • WMI computer as the implementation of Web-basedThink 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• Everydatabase 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
  • 27. To figure out how to query WMI viaVBScript (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.
  • 28. Microsoft Scriptomatic 2.0
  • 29. WMIGen 7.03
  • 30. Option ExplicitDim objWMIService, strComputer, colItemsstrComputer = "."Set objWMIService = GetObject("winmgmts:" & strComputer & "rootCIMV2")On error resume nextSet 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.ServicePackMajorVersionNext 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.
  • 31. Option ExplicitDim objWMIService, strComputer, colItemsstrComputer = "."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.SizeNext 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.
  • 32. Option ExplicitDim strComputer, objWMIService, colItems, strIPAddressstrComputer = "."Set objWMIService = GetObject("winmgmts:" & strComputer & "rootCIMV2")on error resume nextSet colItems = objWMIService.ExecQuery("SELECT * FROMWin32_NetworkAdapterConfiguration", "WQL")For Each objItem In colItems WScript.Echo "Description: " & objItem.Description strIPAddress = Join(objItem.IPAddress, ",") WScript.Echo "IPAddress: " & strIPAddressNext Notice the ‘Join’ function. Some adapters have more than one IP address.
  • 33. • 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
  • 34. Tools you will need• Get AD Object Attributes VBScript http://goo.gl/csLFD• ADExplorer (SysInternals) – find your attributes• ADUC MMC – build your filter
  • 35. The strFilter variable allows you to build your Active Directory filter. You The strAttributes variable should be populated with the fields you wouldcan use the Microsoft ADUC to build this query and paste into this like the script to report back. Things like user name, computervariable. name, account creation date, etc. can be returned…
  • 36. There are MANY ways to getActive Directory data fromyour network.Do what works for you…
  • 37. • 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)
  • 38. <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>
  • 39. <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)”>
  • 40. Tool Link (Case-sensitive)Microsoft Scriptomatic v2.0 http://goo.gl/eL98uMicrosoft HTA-Helpomatic http://goo.gl/cCvDMRob van der Woude’s WMIGen http://goo.gl/jBNkvPSPad Editor http://www.pspad.comNotepad++ Editor http://notepad-plus-plus.org/SysInternals’ ADExplorer http://goo.gl/hzX48Resource Link (Case-sensitive)Microsoft VBScript reference http://goo.gl/uDiFdWScript Host object reference http://goo.gl/uJHWnGet AD Object Attributes Script http://goo.gl/csLFDMicrosoft Script Center http://goo.gl/9BcyDAll built-in VBScript Functions http://goo.gl/iXza8