I have updated this script, changed things to reflect ebgreen's comments as well as added some new stuff
I would've just edited the top post but it seems that I cant, so here it is again:
'Scripting Class examples
'stress the importance of comments!!
'**********************************************************
'basic "Hello World"
WScript.Echo "Hello World!!"
'show concatenation
WScript.Echo "Hello World!!" & " This life is just a test."
'when you need to have quotes in a string
wscript.echo "Hello World ""This life is just a test."""
'**********************************************************
'using a variable
Dim text
text = "Hello World!!"
WScript.Echo text
'array
colors = array("red","blue","green","yellow","black","white")
'explain what an array is and what it is for
'**********************************************************
'using Loops
'using foreach
foreach color in colors
wscript.echo color
next
'using a counter
For i = 1 To 10
WScript.Echo "Loop number: " & i
WScript.Echo text
Next
dim counter
counter = 1
'loop while condition is true
'use do until to loop until something becomes true
do while counter < 10
counter = counter + 1
loop
'**********************************************************
'testing for conditions
Dim test
test = "Howdy World!!"
If test = "Hello World!!" Then
WScript.Echo test & " matches Hello World!!"
Else
WScript.Echo test & " doesn't equal Hello World!!"
End If
'select case
'GOTCHA - only works for strings
foreach color in colors
select case color
case "blue"
wscript.echo "Blue was selected"
case "yellow"
wscript.echo "Yellow was selected"
end case
'notice it will only output "blue" and "yellow" from the array
'you can also use case else before end case
next
'check for the value of an integer
do while counter < 10
if counter < 5 then
wscript.echo "Less than 5"
'demonstrate the elseif
elseif counter = 5 then
wscript.echo "Equals 5"
else
wscript.echo "Greater than 5"
end if
counter = counter + 1
loop
'test for booleans
if test = TRUE then
wscript.echo "Test is true!"
else
wscript.echo "Test is false!"
end if
'there are many other builtin ways to test for things
'**********************************************************
'different types of I/O
'regular echo to screen
WScript.Echo text
'or
WScript.StdOut.Write text
'you can also take input from the commandline like this
'GOTCHA - only works when script is invoked with cscript
'(that is your default scripting host isnt it?)
WScript.StdOut.Writeline "Enter your username (domain\username)"
WScript.StdOut.Write "> "
Username = WScript.StdIn.ReadLine
wscript.echo "You entered: " & Username
'input/msg box
Input = InputBox("Input Something", "Make your selection")
MsgBox("You entered: " & Input)
'fso
'create the object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim outputFile
outputFile = "./output.txt"
Set txtStreamOut = fso.OpenTextFile(OutputFile, 2, True)
WScript.Echo "Writing out to file."
For i = 1 To 10
txtStreamOut.writeline "Loop number: " & i
txtStreamOut.writeline text
Next
'**********************************************************
'subroutines and functions
'good for repetitive code that you want to call over and over
'a general rule of thumb on which to use:
'if you need to return something use a function,
'if you dont, use a subroutine.
'neither will do anything until you call them
'eg add2Array "machine", "file", "missing", "extra", "diff"
'or flyapart "user@domain.com"
'this sub will output to the screen and a file everytime you call it
'notice that it uses the fso object we created above
Sub printOut(data)
WScript.Echo Now() & " --> " & data
txtStreamOut.writeline Now() & " --> " & data
End Sub 'printOut
'subroutine
'this sub also shows a dynamic array, note the redim statement
Sub add2Array(machine,file,missing,extra,diff)
ReDim Preserve outArray(5, arrcount)
outArray(0,arrcount) = machine
outArray(1,arrcount) = file
outArray(2,arrcount) = missing
outArray(3,arrcount) = extra
outArray(4,arrcount) = diff
arrcount = arrcount + 1
End Sub 'add2Array
'function
'in order to return data from a function, set the last variable
'to the same name as the function
Function flyapart(input)
'breaks up email addys and domain logins of all types
'format = domain\username Or username@some.domain.com
If InStr(input, "\") > 0 Then
domain = lcase(Left(input, InStr(input, "\") - 1))
rmEmail = (Len(input)-InStr(input, "\"))
flyapart = lcase(Right(input, rmEmail))
Elseif InStr(input, "@") > 0 Then
rmEmail = (Len(input)-InStr(input, "@")+1)
strToReplace = Right(input, rmEmail)
quickArray = Split(strToReplace, ".")
flyapart = lcase(Replace(input, strToReplace, ""))
domain = LCase(Replace(quickarray(0), "@", ""))
Else
WScript.Echo "That isnt valid input"
End If
End Function 'flyapart
'if you wanted to return multiple values from a function you
'would have to use a global variable or two functions
'**********************************************************
'scripting dictionary
Set objDictionary = CreateObject("Scripting.Dictionary")
'load up the dictionary
For i = 1 To 10
objDictionary.add test & i,i
Next
'the power of the dictionary is the ability to quickly search
If objDictionary.exists("Hello World!!2") Then
WScript.Echo "Hello World!!2 exists in the dictionary with data: " & objDictionary("Hello World!!2")
Else
WScript.Echo "Hello World!!2 doesnt exist in the dictionary"
End If
'output the dictionary
For Each obj In objDictionary
WScript.Echo "The key is: " & obj & " and the associated data is: " & objDictionary(obj)
Next
'**********************************************************
'multidimensional arrays
'2d array that preserves the data if you resize it
ReDim Preserve outArray(5, 0)
add2Array "machine", "file", "missing", "extra", "diff"
add2Array "machine", "file", "missing", "extra", "diff"
add2Array "machine", "file", "missing", "extra", "diff"
outputArray
'the easiest way to increment a dynamic array is use ubound
'GOTCHA - using ubound with multidimensional arrays is a bit different
'Ubound(MyArray,1) 'Returns the Number of Columns
'Ubound(MyArray,2) 'Returns the Number of Rows
'source: http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=190
Sub add2Array(machine,file,missing,extra,diff)
arrcount = ubound(outarray,2)
outArray(0,arrcount) = machine
outArray(1,arrcount) = file
outArray(2,arrcount) = missing
outArray(3,arrcount) = extra
outArray(4,arrcount) = diff
arrcount = arrcount + 1
ReDim Preserve outArray(5, arrcount)
End Sub 'add2Array
'output the array
Sub outputArray()
WScript.Echo "************ detailed output **************"
wscript.echo "machine", "file", "missing", "extra", "diff"
For j = 0 To ubound(outarray,2) -1
WScript.Echo outArray(0,j) & "," & outArray(1,j)& "," & outArray(2,j) _
& "," & outArray(3,j)& "," & outArray(4,j)
Next
End Sub 'outputArray
'**********************************************************
'ADO
'NOTE: This section wont work unless you have the DSN and DB
'setup ahead of time.
'you can use ADO for anything you can store in a recordset
'eg. data from a db, AD, etc
'sql db example
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adUseClient = 3
Set objDBConnection = CreateObject("ADODB.Connection")
Set objDBRecordset = CreateObject("ADODB.Recordset")
'you can make a direct connection or use a windows DSN
objDBConnection.Open "DSN=PROD_DSN","Username","Password"
objDBRecordset.CursorLocation = adUseClient
query = "Select * from table_name;"
objDBRecordset.Open query, objDBConnection, _
adOpenStatic, adLockOptimistic
'loop through the output
While Not objDBRecordset.EOF
WScript.Echo objDBRecordset.Fields("Field Name")
Wend
'close everything
objDBRecordset.Close
objDBConnection.Close
Set objDBRecordSet = Nothing
Set objDBConnection = Nothing
'**********************************************************
'WMI & WQL
'the dot represents the local machine, just put in the hostname
'of the remote computer and it will get the info from it instead
strComputer = "."
'WMI namespace to get the data from
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
'WQL query, very similar to SQL
Set colSettings = objWMIService.ExecQuery _
("Select * from Win32_ComputerSystem")
'iterate through the results
For Each objComputer in colSettings
Wscript.Echo "System Name: " & objComputer.Name
Wscript.Echo "System Manufacturer: " & objComputer.Manufacturer
Wscript.Echo "System Model: " & objComputer.Model
Wscript.Echo "Time Zone: " & objComputer.CurrentTimeZone
Wscript.Echo "Total Physical Memory: " & _
objComputer.TotalPhysicalMemory
Next
'**********************************************************
'ADSI
'you use the ADO record set to return data from AD as well
'NOTE there is a 1000 record limit for data returned in AD
Set objADConnection = CreateObject("ADODB.Connection")
objADConnection.Open "Provider=ADsDSOObject;"
Set objADCommand = CreateObject("ADODB.Command")
objADCommand.ActiveConnection = objADConnection
'the following line will allow you to pull more than 1k objects out of AD
objADCommand.Properties("Page Size") = 1000
'there are two kinds of queries, a LDAP query and Global Catalog query
'the syntax is the same: <query_type>;query;returned_values;scope(recurisve or not)
'GC query, you are able to do general queries but the GC doesnt store all attributes
objGCCommand.CommandText = _
"<GC://dc=domain,dc=net>;(&((objectClass=User)(extensionAttribute1='10')));"_
& "name,mail;subtree"
'LDAP query, note you have to give the full LDAP path to the object
objLDAPCommand.CommandText = _
"<LDAP://ou=terminated,ou=people,dc=domain,dc=com>;(objectCategory=Group);" & _
"distinguishedName,primaryGroupToken;subtree"
Set objADRecordSet = objADCommand.Execute
While Not objADRecordSet.EOF
WScript.Echo objADRecordSet.Fields("name")
Wend
'close And clear the recordset
objADRecordSet.Close
Set objADRecordSet = Nothing