View Scripts of choice:
Bind to Active Directory using rootDSE
Script About: Scripting Techniques
Demonstration script that uses rootDSE to bind to various objects in the local Active Directory domain.
Set objRootDSE = GetObject("LDAP://rootDSE")
 
strSchema = "LDAP://" & objRootDSE.Get("schemaNamingContext")
WScript.echo "ADsPath to schema: " & strSchema
Set objSchema = GetObject(strSchema)
WScript.Echo "Schema Object:"
WScript.Echo "Name: " & objSchema.Name
WScript.Echo "Class: " & objSchema.Class & VbCrLf
 
strConfiguration = "LDAP://" & objRootDSE.Get("configurationNamingContext")
WScript.Echo "ADsPath to configuration container: " & strConfiguration
Set objConfiguration = GetObject(strConfiguration)
WScript.Echo "Configuration Object:"
WScript.Echo "Name: " & objConfiguration.Name
WScript.Echo "Class: " & objConfiguration.Class & VbCrLf
 
strDomain = "LDAP://" & objRootDSE.Get("defaultNamingContext")
WScript.Echo "ADsPath to current domain container: " & strDomain
Set objDomain = GetObject(strDomain)
WScript.Echo "Current Domain Object:"
WScript.Echo "Name: " & objDomain.Name
WScript.Echo "Class: " & objDomain.Class & VbCrLf
 
strRootDomain = "LDAP://" & objRootDSE.Get("rootDomainNamingContext")
WScript.Echo "ADsPath to root domain container: " & strDomain
Set objRootDomain = GetObject(strRootDomain)
WScript.Echo "Current Domain Object:"
WScript.Echo "Name: " & objRootDomain.Name
WScript.Echo "Class: " & objRootDomain.Class & VbCrLf
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List Active Directory Auxiliary Classes
Script About: Scripting Techniques
Returns a list of all the Active Directory auxiliary classes directly applied to the User class.
On Error Resume Next

strClassName = "cn=user"
 
Set objSchemaClass = GetObject _
    ("LDAP://" & strClassName & _
        ",cn=schema,cn=configuration,dc=fabrikam,dc=com")
 
arrSystemAuxiliaryClass = _
objSchemaClass.GetEx("systemAuxiliaryClass")
 
If isEmpty(arrSystemAuxiliaryClass) Then
    WScript.Echo "There are no auxiliary classes" & _
        " applied directly to this class."
    Else
        WScript.StdOut.Write "Auxiliary classes: "
    For Each strAuxiliaryClass in arrSystemAuxiliaryClass
        WScript.StdOut.Write strAuxiliaryClass & " | "
    Next
    WScript.Echo
End If
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List Active Directory System Information
Script About: Scripting Techniques
Uses the ADSystemInfo interface to return domain information for a computer, including computer name, site name, and various domain names (short name, domain DNS name, and forest DNS name).
On Error Resume Next
Set objSysInfo = CreateObject("ADSystemInfo")

Wscript.Echo "User name: " & objSysInfo.UserName
Wscript.Echo "Computer name: " & objSysInfo.ComputerName
Wscript.Echo "Site name: " & objSysInfo.SiteName
Wscript.Echo "Domain short name: " & objSysInfo.DomainShortName
Wscript.Echo "Domain DNS name: " & objSysInfo.DomainDNSName
Wscript.Echo "Forest DNS name: " & objSysInfo.ForestDNSName
Wscript.Echo "PDC role owner: " & objSysInfo.PDCRoleOwner
Wscript.Echo "Schema role owner: " & objSysInfo.SchemaRoleOwner
Wscript.Echo "Domain is in native mode: " & objSysInfo.IsNativeMode
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesNoNo
List All the Attributes of an Active Directory Class
Script About: Scripting Techniques
Returns all the attributes associated with the Computer class in Active Directory.
Set objSchemaComputer = GetObject("LDAP://schema/computer")
 
WScript.Echo "Mandatory (Must-Contain) attributes"
For Each strAttribute in objSchemaComputer.MandatoryProperties
    WScript.Echo strAttribute
Next
 
WScript.Echo VbCrLf & "Optional (May-Contain) attributes"
For Each strAttribute in objSchemaComputer.OptionalProperties
    WScript.Echo strAttribute
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List Domain Object Property Values
Script About: Scripting Techniques
Retrieves the ADsPath, Class, GUID, Name, Parent, and Schema properties for a domain.
Set objDomain = GetObject("LDAP://dc=NA,dc=fabrikam,dc=com")

WScript.Echo "Ads Path:" & objDomain.ADsPath
WScript.Echo "Class:" & objDomain.Class
WScript.Echo "GUID:" & objDomain.GUID
WScript.Echo "Name:" & objDomain.Name
WScript.Echo "Parent:" & objDomain.Parent
WScript.Echo "Schema:" & objDomain.Schema
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List the Active Directory Class Type for an Object
Script About: Scripting Techniques
Determines the Active Directory class type for the organizational-person object.
strClassName = "cn=organizational-person"
 
Set objSchemaClass = GetObject _
    ("LDAP://" & strClassName & _
        ",cn=schema,cn=configuration,dc=fabrikam,dc=com")
 
intClassCategory = objSchemaClass.Get("objectClassCategory")

Select Case intClassCategory
    Case 0
        strCategory = "88"
    Case 1
        strCategory = "structural"
    Case 2
        strCategory = "abstract"
    Case 3
        strCategory = "auxiliary"
End Select

Wscript.Echo strClassName & " is categorized as " & strCategory & "."
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List the Names of All Objects in the Configuration Container
Script About: Scripting Techniques
Retrieves the names of the first-level objects in the Configuration container.
Set objConfiguration = GetObject _
    ("LDAP://cn=Configuration,dc=fabrikam,dc=com")
 
For Each objContainer in objConfiguration
    WScript.Echo objContainer.Name
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List the Parent Class of an Active Directory Object
Script About: Scripting Techniques
Determines the parent class of the Computer object within Active Directory.
strClassName = "cn=computer"
 
Set objSchemaClass = GetObject _
    ("LDAP://" & strClassName & _
        ",cn=schema,cn=configuration,dc=fabrikam,dc=com")
 
strSubClassOf = objSchemaClass.Get("subClassOf")
WScript.Echo "The " & strClassName & _
    " class is a child of the " & strSubClassOf & " class."
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Use a Search to Move Similar Active Directory Objects
Script About: Scripting Techniques
Searches for all user account objects whose department attribute is Human Resources. The script then moves the user accounts that are not already in the HR OU to this OU.
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"
 
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
 
objCommand.CommandText = _
    ";" & _
        "(&(&(objectCategory=person)(objectClass=user)" & _
            "(department=Human Resources)));" & _
                "ADsPath,distinguishedName, name;subtree"
  
Set objRecordSet = objCommand.Execute
Set objOU = GetObject("LDAP://ou=HR,dc=NA,dc=fabrikam,dc=com")
 
Do Until objRecordset.EOF
    strADsPath = objRecordset.Fields("ADsPath")
  
    strDNRecord=lcase(objRecordset.Fields("distinguishedName"))
    strDNCompare=lcase("cn=" & objRecordset.Fields("name") & _
        ",ou=HR,dc=NA,dc=fabrikam,dc=com")
 
    If strDNRecord <> strDNCompare Then
        objOU.MoveHere strADsPath, vbNullString
        WScript.Echo objRecordset.Fields("distinguishedName") & " Moved."
    Else
        Wscript.Echo objRecordset.Fields("distinguishedName") & " Not Moved."
    End If
    objRecordSet.MoveNext
Loop
 
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Use a Search to Modify Similar Active Directory Objects
Script About: Scripting Techniques
Searches for all computers that begin with the letters "ATL" in a domain and any child domain, and then modifies the location attribute of all computers found.
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"
 
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
 
objCommand.CommandText = _
    ";" & _
        "(&(objectCategory=Computer)(cn=ATL*));" & _
            "ADsPath;subtree"
  
Set objRecordSet = objCommand.Execute
 
Do Until objRecordset.EOF
    strADsPath = objRecordset.Fields("ADsPath")
    Set objComputer = GetObject(strADsPath)
    objComputer.Put "location", "Atlanta, Georgia"
    objComputer.SetInfo
    objRecordSet.MoveNext
Loop
 
WScript.Echo objRecordSet.RecordCount & _
   " computers objects modified."
 
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Verify That an Attribute is in the Global Catalog
Script About: Scripting Techniques
Determines whether or not a specified attribute (given-name) is included in the Active Directory global catalog.
strAttributeName = "cn=given-name"
 
Set objSchemaAttribute = GetObject _
    ("LDAP://" & strAttributeName & _
        ",cn=schema,cn=configuration,dc=fabrikam,dc=com") 
 
blnInGC = objSchemaAttribute.Get("isMemberOfPartialAttributeSet")
 
If blnInGC Then
    WScript.Echo "The " & strAttributeName & _
        " attribute is replicated to the Global Catalog."
Else
    WScript.Echo "The " & strAttributeName & _
        " attribute is not replicated to the Global Catalog."
End If
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Verify That an Attribute is Operational
Script About: Scripting Techniques
Determines whether or not a specified attribute (Canonical-Name) is operational within Active Directory.
Const ADS_SYSTEMFLAG_ATTR_IS_CONSTRUCTED = &h00000004
 
strAttributeName = "cn=Canonical-Name"
 
Set objSchemaAttribute = GetObject _
    ("LDAP://" & strAttributeName & _
        ",cn=schema,cn=configuration,dc=fabrikam,dc=com")
 
intSystemFlags = objSchemaAttribute.Get("systemFlags")
 
If intSystemFlags AND ADS_SYSTEMFLAG_ATTR_IS_CONSTRUCTED Then
    WScript.Echo strAttributeName & " is operational."
Else
    WScript.Echo strAttributeName & " is not operational."
End If
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Verify Whether Attributes are Indexed and-or in the Global Catalog
Script About: Scripting Techniques
Determines which Active Directory attributes are indexed and which attributes are in the global catalog.
Const IS_INDEXED = 1
 
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"
 
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
 
objCommand.Properties("Sort On") = "isMemberOfPartialAttributeSet" 
 
objCommand.CommandText = _
    ";" & _
        "(objectClass=attributeSchema);" & _
            "lDAPDisplayName, isMemberOfPartialAttributeSet,searchFlags;onelevel"
 
Set objRecordSet = objCommand.Execute
 
Do Until objRecordSet.EOF
    WScript.Echo objRecordset.Fields("lDAPDisplayName") 
    If objRecordset.Fields("isMemberOfPartialAttributeSet")Then
        WScript.Echo "In the global catalog."
    Else
        WScript.Echo "Not in the global catlog."
    End If
 
    If IS_INDEXED AND objRecordset.Fields("searchFlags") Then
        WScript.Echo "Is indexed."
    Else
        WScript.Echo "Is not indexed."
    End If
    Wscript.Echo VbCrLf
    objRecordSet.MoveNext
Loop
 
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Create Documentation Based on Script Comments
Script About: Scripting Techniques
Demonstrates the use of the FileSystemObject as a way to copy comments from a script to a separate text file. Requires comments to have been marked using '*.
Const ForReading = 1
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objScriptFile = objFSO.OpenTextFile("c:\scripts\Service_Monitor.vbs", _
    ForReading)
Set objCommentFile = objFSO.OpenTextFile("c:\scripts\Comments.txt", _ 
    ForWriting, TRUE)

Do While objScriptFile.AtEndOfStream <> TRUE
    strCurrentLine = objScriptFile.ReadLine
    intIsComment = Instr(1,strCurrentLine,"'*")
    If intIsComment > 0 Then
        objCommentFile.Write strCurrentLine & VbCrLf
    End If
Loop

objScriptFile.Close
objCommentFile.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Delete Debugging Comments
Script About: Scripting Techniques
Demonstrates the use of the FileSystemObject as a way to remove debugging comments from a script. Requires comments to have been marked as '* BUG.
Const ForReading = 1
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("C:\Scripts\CreateUser.vbs", ForReading)
 
Do While objTextFile.AtEndOfStream <> true
    strNextLine = objTextFile.Readline
    intCheckForBugComment = Instr(strNextLine, "'* BUG")
    If intCheckForBugComment = 0 Then
        strSavedLines = strSavedLines & strNextLine & VbCrLf
    End If
Loop
 
Set objTextFile = objFSO.OpenTextFile _
    ("c:\scripts\CreateUser.vbs ", ForWriting)
objTextFile.Write strSavedLines 
objTextFile.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Convert WMI Date-Time Values
Script About: Scripting Techniques
Demonstrates a method for converting the Universal Time Coordinate (UTC) values used by WMI to standard date-time values. The script retrieves the date that the operating system was installed, and passes that UTC value to a function named WMIDateStringToDate. This function converts the UTC value (such as 20011029113047.000000-480) to a standard date-time value (such as 10/29/200111:30:47 AM).
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set objOS = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")
 
For Each strOS in objOS
    dtmInstallDate = strOS.InstallDate
    strReturn = WMIDateStringToDate(dtmInstallDate)
    Wscript.Echo strReturn 
Next
 
Function WMIDateStringToDate(dtmInstallDate)
    WMIDateStringToDate = CDate(Mid(dtmInstallDate, 5, 2) & "/" & _
        Mid(dtmInstallDate, 7, 2) & "/" & Left(dtmInstallDate, 4) _
            & " " & Mid (dtmInstallDate, 9, 2) & ":" & _
                Mid(dtmInstallDate, 11, 2) & ":" & Mid(dtmInstallDate, _
                    13, 2))
End Function
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List the UTC Time on a Computer
Script About: Scripting Techniques
Reports the Universal Time Coordinate (UTC) time on a computer.
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery("Select * from Win32_UTCTime")

For Each objItem in colItems
    Wscript.Echo "Day: " & objItem.Day
    Wscript.Echo "Day of the Week: " & objItem.DayOfWeek
    Wscript.Echo "Hour: " & objItem.Hour
    Wscript.Echo "Milliseconds: " & objItem.Milliseconds
    Wscript.Echo "Minute: " & objItem.Minute
    Wscript.Echo "Month: " & objItem.Month
    Wscript.Echo "Quarter: " & objItem.Quarter
    Wscript.Echo "Second: " & objItem.Second
    Wscript.Echo "Week in the Month: " & objItem.WeekInMonth
    Wscript.Echo "Year: " & objItem.Year
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesNoNoNo
List the UTC Time on a Computer
Script About: Scripting Techniques
Reports the Universal Time Coordinate (UTC) time on a computer.
var wbemFlagReturnImmediately = 0x10;
var wbemFlagForwardOnly = 0x20;

   var objWMIService = GetObject("winmgmts:\\\\.\\root\\CIMV2");
   var colItems = objWMIService.ExecQuery("SELECT * FROM Win32_UTCTime", "WQL",
                                          wbemFlagReturnImmediately | wbemFlagForwardOnly);

   var enumItems = new Enumerator(colItems);
   for (; !enumItems.atEnd(); enumItems.moveNext()) {
      var objItem = enumItems.item();

      WScript.Echo("Day: " + objItem.Day);
      WScript.Echo("Day Of Week: " + objItem.DayOfWeek);
      WScript.Echo("Hour: " + objItem.Hour);
      WScript.Echo("Milliseconds: " + objItem.Milliseconds);
      WScript.Echo("Minute: " + objItem.Minute);
      WScript.Echo("Month: " + objItem.Month);
      WScript.Echo("Quarter: " + objItem.Quarter);
      WScript.Echo("Second: " + objItem.Second);
      WScript.Echo("Week In Month: " + objItem.WeekInMonth);
      WScript.Echo("Year: " + objItem.Year);
      WScript.Echo();
   }
Platform SupportLanguage Support:Jscript
Win2003WinXPWin2000WinNTWin98
YesYesNoNoNo
List the UTC Time on a Computer
Script About: Scripting Techniques
Reports the Universal Time Coordinate (UTC) time on a computer.
use Win32::OLE('in');
use constant wbemFlagReturnImmediately => 0x10;
use constant wbemFlagForwardOnly => 0x20;

$computer = ".";
$objWMIService = Win32::OLE->GetObject
    ("winmgmts:\\\\$computer\\root\\CIMV2") or die "WMI connection failed.\n";
$colItems = $objWMIService->ExecQuery
    ("SELECT * FROM Win32_UTCTime","WQL",wbemFlagReturnImmediately | wbemFlagForwardOnly);

foreach my $objItem (in $colItems)
{
      print "Day: $objItem->{Day}\n";
      print "Day Of Week: $objItem->{DayOfWeek}\n";
      print "Hour: $objItem->{Hour}\n";
      print "Milliseconds: $objItem->{Milliseconds}\n";
      print "Minute: $objItem->{Minute}\n";
      print "Month: $objItem->{Month}\n";
      print "Quarter: $objItem->{Quarter}\n";
      print "Second: $objItem->{Second}\n";
      print "Week In Month: $objItem->{WeekInMonth}\n";
      print "Year: $objItem->{Year}\n";
      print "\n";
}
Platform SupportLanguage Support:Perl
Win2003WinXPWin2000WinNTWin98
YesYesNoNoNo
List the UTC Time on a Computer
Script About: Scripting Techniques
Reports the Universal Time Coordinate (UTC) time on a computer.
strComputer = "."
objWMIService = .OLEObject~GetObject("winmgmts:\\"||strComputer||"\root\CIMV2")
do objItem over objWMIService~ExecQuery("Select * from Win32_UTCTime")
    say "Day:" objItem~Day
    say "Day Of Week:" objItem~DayOfWeek
    say "Hour:" objItem~Hour
    say "Milliseconds:" objItem~Milliseconds
    say "Minute:" objItem~Minute
    say "Month:" objItem~Month
    say "Quarter:" objItem~Quarter
    say "Second:" objItem~Second
    say "Week In Month:" objItem~WeekInMonth
    say "Year:" objItem~Year
end
Platform SupportLanguage Support:Rexx
Win2003WinXPWin2000WinNTWin98
YesYesNoNoNo
List the UTC Time on a Computer
Script About: Scripting Techniques
Reports the Universal Time Coordinate (UTC) time on a computer.
import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_UTCTime")
for objItem in colItems:
    print "Day: ", objItem.Day
    print "Day Of Week: ", objItem.DayOfWeek
    print "Hour: ", objItem.Hour
    print "Milliseconds: ", objItem.Milliseconds
    print "Minute: ", objItem.Minute
    print "Month: ", objItem.Month
    print "Quarter: ", objItem.Quarter
    print "Second: ", objItem.Second
    print "Week In Month: ", objItem.WeekInMonth
    print "Year: ", objItem.Year
Platform SupportLanguage Support:Python
Win2003WinXPWin2000WinNTWin98
YesYesNoNoNo
List the UTC Time on a Computer
Script About: Scripting Techniques
Reports the Universal Time Coordinate (UTC) time on a computer.
$strComputer = "."
$objWMIService = GetObject("winmgmts:\\"+ $strComputer + "\root\cimv2")
$colItems = $objWMIService.ExecQuery("Select * from Win32_UTCTime")
For Each $objItem in $colItems
    ? "Day:" + $objItem.Day
    ? "Day Of Week:" + $objItem.DayOfWeek
    ? "Hour:" + $objItem.Hour
    ? "Milliseconds:" + $objItem.Milliseconds
    ? "Minute:" + $objItem.Minute
    ? "Month:" + $objItem.Month
    ? "Quarter:" + $objItem.Quarter
    ? "Second:" + $objItem.Second
    ? "Week In Month:" + $objItem.WeekInMonth
    ? "Year:" + $objItem.Year
Next
Platform SupportLanguage Support:Kixtart
Win2003WinXPWin2000WinNTWin98
YesYesNoNoNo
Locate a File Using a File Open Dialog Box
Script About: Scripting Techniques
Demonstration script that displays a File Open dialog box (open to the folder C:\Scripts), and then echoes back the name of the selected file.
Set objDialog = CreateObject("UserAccounts.CommonDialog")

objDialog.Filter = "VBScript Scripts|*.vbs|All Files|*.*"
objDialog.FilterIndex = 1
objDialog.InitialDir = "C:\Scripts"
intResult = objDialog.ShowOpen
 
If intResult = 0 Then
    Wscript.Quit
Else
    Wscript.Echo objDialog.FileName
End If
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
NoYesNoNoNo
Save a File Using a File Save Dialog Box
Script About: Scripting Techniques
Demonstration script that allows you to enter a file name in a File Save dialog box, and then saves a sample text file (consisting entirely of the current date) under that file name.
Set objDialog = CreateObject("SAFRCFileDlg.FileSave")

objDialog.FileName = "C:\Scripts\Script1.vbs"
objDialog.FileType = "VBScript Script"
intReturn = objDialog.OpenFileSaveDlg

If intReturn Then
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.CreateTextFile(objDialog.FileName)
    objFile.WriteLine Date
    objFile.Close
Else
    Wscript.Quit
End If
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
NoYesNoNoNo
Add Elements to a Dictionary
Script About: Scripting Techniques
Demonstration script that adds three key-item pairs to a Script Runtime Dictionary. Script must be run on the local computer.
Set objDictionary = CreateObject("Scripting.Dictionary")

objDictionary.Add "Printer 1", "Printing"   
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Delete All Elements from a Dictionary
Script About: Scripting Techniques
Demonstration script that deletes all the key-item pairs from a Script Runtime Dictionary. Script must be run on the local computer.
Set objDictionary = CreateObject("Scripting.Dictionary")

objDictionary.Add "Printer 1", "Printing"   
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"
colKeys = objDictionary.Keys

Wscript.Echo "First run: "
For Each strKey in colKeys
    Wscript.Echo strKey
Next

objDictionary.RemoveAll
colKeys = objDictionary.Keys

Wscript.Echo VbCrLf & "Second run: "
For Each strKey in colKeys
    Wscript.Echo strKey
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Delete One Element from a Dictionary
Script About: Scripting Techniques
Demonstration script that deletes a specific key-item pair from a Script Runtime Dictionary. Script must be run on the local computer.
Set objDictionary = CreateObject("Scripting.Dictionary")

objDictionary.Add "Printer 1", "Printing"   
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"

colKeys = objDictionary.Keys

Wscript.Echo "First run: " 
For Each strKey in colKeys
    Wscript.Echo strKey
Next
 
objDictionary.Remove("Printer 2")
colKeys = objDictionary.Keys

Wscript.Echo VbCrLf & "Second run: " 
For Each strKey in colKeys
    Wscript.Echo strKey
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List the Number of Items in a Dictionary
Script About: Scripting Techniques
Demonstration script that counts the number of key-item pairs in a Script Runtime Dictionary. Script must be run on the local computer.
Set objDictionary = CreateObject("Scripting.Dictionary")

objDictionary.Add "Printer 1", "Printing"   
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"
Wscript.Echo objDictionary.Count
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Verify the Existence of a Dictionary Key
Script About: Scripting Techniques
Demonstration script that verifies the existence of a particular key within a Script Runtime Dictionary. Script must be run on the local computer.
Set objDictionary = CreateObject("Scripting.Dictionary")

objDictionary.Add "Printer 1", "Printing"   
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"

If objDictionary.Exists("Printer 4") Then
    Wscript.Echo "Printer 4 is in the Dictionary."
Else
    Wscript.Echo "Printer 4 is not in the Dictionary."
End If
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List Real Time Events in a Command Window
Script About: Scripting Techniques
Creates a temporary event consumer that monitors the event log for error events. When an error event occurs, the script displays the event information in the command window.
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate,(Security)}!\\" & _
        strComputer & "\root\cimv2")

Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
    ("Select * from __InstanceCreationEvent within 5 where TargetInstance " & _
        isa 'Win32_NTLogEvent' and TargetInstance.EventType = '1'")

Do
    Set objLatestEvent = colMonitoredEvents.NextEvent
        Wscript.Echo "Record No.: " & _
            objLatestEvent.TargetInstance.RecordNumber
        Wscript.Echo "Event ID: " & objLatestEvent.TargetInstance.EventCode
        Wscript.Echo "Time: " & objLatestEvent.TargetInstance.TimeWritten
        Wscript.Echo "Source: " & objLatestEvent.TargetInstance.SourceName
        Wscript.Echo "Category: " & _
            objLatestEvent.TargetInstance.CategoryString
        Wscript.Echo "Event Type: " & objLatestEvent.TargetInstance.Type
        Wscript.Echo "Computer: " & _
            objLatestEvent.TargetInstance.ComputerName
        Wscript.Echo "User: " & objLatestEvent.TargetInstance.User
        Wscript.echo "Text: " & objLatestEvent.TargetInstance.Message
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesNo
List Tabular Output in a Command Window
Script About: Scripting Techniques
Retrieves service data from a computer, and then outputs that data in tabular format in a command window.
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colServices = objWMIService.ExecQuery("Select * from Win32_Service")

For Each objService in colServices
    intPadding = 50 - Len(objService.DisplayName)
    intPadding2 = 17 - Len(objService.StartMode)
    strDisplayName = objService.DisplayName & Space(intPadding)
    strStartMode = objService.StartMode & Space(intPadding2)
    Wscript.Echo strDisplayName & strStartMode & objService.State 
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Sort WMI Data
Script About: Scripting Techniques
Demonstration script showing how WMI data can be sorted using a disconnected recordset (by itself, WMI does not allow you to specify a sort order for returned data). In this script, service information is retrieved using WMI and is stored in a disconnected recordset, a recordset that is not tied to a physical data source. The Sort method is then used to sort the service data by service state rather than by service name.
dtmStartTime = Now

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objDiskDrives = objWMIService.ExecQuery _
    ("Select * from Win32_LogicalDisk")

For Each objDrive in objDiskDrives
    If objDrive.FreeSpace < 10000000 Then
        Wscript.Echo "Drive is low on disk space."
    End If
Next

Do
    Set objDiskDrives = objWMIService.ExecQuery _
        ("Select * from Win32_LogicalDisk")
    For Each objDrive in objDiskDrives
        If objDrive.FreeSpace < 10000000 Then
            intElapsedHours = DateDiff("h", dtmStartTime, Now)
                If intElapsedHours >= 1 Then
                    Wscript.Echo "Drive is low on disk space." 
                dtmStartTime = Now
            End If  
        End If
    Next
    Wscript.Sleep 1000
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Suppress Multiple Event Notifications
Script About: Scripting Techniques
Issues an alert if available space on a disk drive falls below 100 megabytes. Will wait one hour before issuing the next alert.
dtmStartTime = Now
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set objDiskDrives = objWMIService.ExecQuery _
    ("Select * from Win32_LogicalDisk")

For Each objDrive in objDiskDrives
    If objDrive.FreeSpace < 10000000 Then
        Wscript.Echo "Drive is low on disk space."
    End If
Next

Do
    Set objDiskDrives = objWMIService.ExecQuery _
        ("Select * from Win32_LogicalDisk")
    For Each objDrive in objDiskDrives
        If objDrive.FreeSpace < 10000000 Then
            intElapsedHours = DateDiff("h", dtmStartTime, Now)
            If intElapsedHours >= 1 Then
                Wscript.Echo "Drive is low on disk space." 
                dtmStartTime = Now
            End If  
        End If
    Next
    Wscript.Sleep 1000
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Mask Command Line Passwords
Script About: Scripting Techniques
Demonstration script that uses ScriptPW.dll to mask passwords entered at the command line.
Set objPassword = CreateObject("ScriptPW.Password") 
WScript.StdOut.Write "Please enter your password:" 

strPassword = objPassword.GetPassword() 
Wscript.Echo
Wscript.Echo "Your password is: " & strPassword
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesNoNoNo
Mask Passwords Using Internet Explorer
Script About: Scripting Techniques
Demonstration script that creates an instance of Internet Explorer, and retrieves a password typed into a password-style text box. Requires a Web page named password.htm with the appropriate text box.
Set objExplorer = WScript.CreateObject _
    ("InternetExplorer.Application", "IE_")

objExplorer.Navigate "file:///c:\scripts\password.htm"   
objExplorer.Visible = 1             
objExplorer.ToolBar = 0
objExplorer.StatusBar = 0
objExplorer.Width=400
objExplorer.Height = 250 
objExplorer.Left = 0
objExplorer.Top = 0

Do While (objExplorer.Document.Body.All.OKClicked.Value = "")
    Wscript.Sleep 250                 
Loop 

strPassword = objExplorer.Document.Body.All.PasswordBox.Value
objExplorer.Quit

Wscript.Sleep 250
Wscript.Echo strPassword
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Track Script Progress in a Command Window
Script About: Scripting Techniques
Demonstrates the use of StdOut as a method for indicating the progress being made by a script.
Wscript.Echo "Processing information. This might take several minutes."

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colServices = objWMIService.ExecQuery("Select * from Win32_Service")

For Each objService in colServices
    Wscript.StdOut.Write(".")
Next

Wscript.StdOut.WriteLine
Wscript.Echo "Service information processed."
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Track Script Progress Using Internet Explorer
Script About: Scripting Techniques
Demonstrates how to use Internet Explorer as a method for indicating the progress being made by a script.
Set objExplorer = WScript.CreateObject("InternetExplorer.Application")
objExplorer.Navigate "about:blank"   
objExplorer.ToolBar = 0
objExplorer.StatusBar = 0
objExplorer.Width=400
objExplorer.Height = 200 
objExplorer.Left = 0
objExplorer.Top = 0

Do While (objExplorer.Busy)
    Wscript.Sleep 200
Loop    

objExplorer.Visible = 1             
objExplorer.Document.Body.InnerHTML = "Retrieving service information. " _
    & "This might take several minutes to complete."

strComputer = "."
Set colServices = GetObject("winmgmts:\\" & strComputer & "\root\cimv2"). _
    ExecQuery("Select * from Win32_Service")
For Each objService in colServices
    Wscript.Sleep 200
Next

objExplorer.Document.Body.InnerHTML = "Service information retrieved."
Wscript.Sleep 3000
objExplorer.Quit
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Read Arguments from a Text File
Script About: Scripting Techniques
Demonstration script that opens a hypothetical text file consisting of server names, then retrieves service information from each on the servers in the file.
Const ForReading = 1

Set objDictionary = CreateObject("Scripting.Dictionary")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("c:\scripts\servers.txt", ForReading)
i = 0

Do Until objTextFile.AtEndOfStream 
    strNextLine = objTextFile.Readline
    objDictionary.Add i, strNextLine
    i = i + 1
Loop

For Each objItem in objDictionary
    Set colServices = GetObject("winmgmts://" & _
        objDictionary.Item(objItem) _
            & "").ExecQuery("Select * from Win32_Service")
    Wscript.Echo colServices.Count
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Read Arguments from an Active Directory Container
Script About: Scripting Techniques
Demonstration script that retrieves the names of all the computers in an Active Directory container, and then returns service information from each of those computers.
Set objDictionary = CreateObject("Scripting.Dictionary")

i = 0
Set objOU = GetObject("LDAP://CN=Computers, DC=fabrikam, DC=com")
objOU.Filter = Array("Computer")

For Each objComputer in objOU 
    objDictionary.Add i, objComputer.CN
    i = i + 1
Next

For Each objItem in objDictionary
    Set colServices = GetObject("winmgmts://" & _
        objDictionary.Item(objItem) _
            & "").ExecQuery("Select * from Win32_Service")
    Wscript.Echo colServices.Count
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Use a Text File as a Command Line Argument
Script About: Scripting Techniques
Demonstration script that allows you to drag a text file (consisting of server names) onto the script icon in Windows Explorer. The script then opens the text file, then retrieves service information from each on the servers in the file.
Const ForReading = 1
Set objArgs = WScript.Arguments

Set objDictionary = CreateObject("Scripting.Dictionary")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile(objArgs(0), ForReading)
i = 0
 
Do While objTextFile.AtEndOfStream <> True
  strNextLine = objTextFile.Readline
  objDictionary.Add i, strNextLine
  i = i + 1
Loop
 
For Each objItem in objDictionary
  Set colServices = GetObject("winmgmts://" & objDictionary.Item(objItem) _
      & "").ExecQuery("Select * from Win32_Service")
  Wscript.Echo colServices.Count
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List the Contents of a Web Page
Script About: Scripting Techniques
Retrieves the HTML source for the Web page http://www.microsoft.com. This script contributed by Maxim Stepin of Microsoft.
url="http://www.microsoft.com"
Set objHTTP = CreateObject("MSXML2.XMLHTTP")

Call objHTTP.Open("GET", url, FALSE)
objHTTP.Send

WScript.Echo(objHTTP.ResponseText)
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Save an RSS Feed to a Text File
Script About: Scripting Techniques
Sample script that connects to a Web site that supports RSS feeds and then saves the returned data to an XML file named C:\Scripts\Scripting_guys.xml.
Const ForWriting = 2

strURL="http://blogs.msdn.com/gstemp/Rss.aspx"
Set objHTTP = CreateObject("MSXML2.XMLHTTP") 
Call objHTTP.Open("GET", strURL, FALSE) 
objHTTP.Send

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile _
    ("C:\Scripts\scripting_guys.xml", ForWriting)
objFile.Write objHTTP.ResponseText
objFile.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesNoNoNo
Add Specific Users to a Group
Script About: Scripting Techniques
Demonstration script that searches for all Accountants in the fabrikam.com domain and then adds all those user accounts to the Accountants security group.
On Error Resume Next

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection
objCommand.CommandText = _
    "SELECT ADsPath FROM 'LDAP://DC=fabrikam,DC=com' " _
        & "WHERE objectCategory='User' AND Title='Accountant'"  
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 
Set objRecordSet = objCommand.Execute

Set objGroup = GetObject _
    ("LDAP://cn=Accountants,ou=NA,dc=fabrikam,dc=com")
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    objGroup.Add(objRecordSet.Fields("ADsPath").Value)
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Create a Department Phone List
Script About: Scripting Techniques
Demonstration script that develops a department phone list for the Finance Department of fabrikam.com.
On Error Resume Next

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection
objCommand.CommandText = _
    "SELECT givenName,SN,telephoneNumber FROM " & _
        "'LDAP://DC=fabrikam,DC=com' " _
            & "WHERE objectCategory='User' AND department='Finance'"  
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("SN").Value & ", " & _
        objRecordSet.Fields("givenName").Value & " " & _
            objRecordSet.Fields("telephoneNumber").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Perform a Search Using Alternate Credentials
Script About: Scripting Techniques
Demonstration script that searches Active Directory under alternate credentials.
On Error Resume Next

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Properties("User ID") = "Administrator"
objConnection.Properties("Password") = "+77m5trgJo!"
objConnection.Properties("Encrypt Password") = TRUE
objConnection.Properties("ADSI Flag") = 1
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 

objCommand.CommandText = _
    "SELECT Name FROM 'LDAP://dc=fabrikam,dc=com' WHERE objectCategory='user'"  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("Name").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search for a SAM Account Name
Script About: Scripting Techniques
Demonstration script that determines whether the samAccountName kenmyer has already been assigned in Active Directory.
On Error Resume Next

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = ("ADsDSOObject")
objConnection.Open "Active Directory Provider"
objCommand.ActiveConnection = objConnection
objCommand.CommandText = "SELECT samAccountName FROM " & _
    "'LDAP://dc=fabrikam,dc=com' " & _
        "WHERE samAccountName = 'kenmyer'"
objCommand.Properties("SearchScope") = ADS_SCOPE_SUBTREE
Set objRecordSet = objCommand.Execute

If objRecordSet.RecordCount = 0 Then
    Wscript.Echo "The samAccount name is not being used."
Else
    Wscript.Echo "The samAccount name is being used."
End If
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search for All Groups in Active Directory
Script About: Scripting Techniques
Demonstration script that returns the names of all the groups in Active Directory.
On Error Resume Next

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 

objCommand.CommandText = _
    "SELECT cn FROM 'LDAP://dc=fabrikam,dc=com' WHERE " _
        & "objectCategory='group'"  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("cn").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search for All Non-User Accounts
Script About: Scripting Techniques
Demonstration script that returns all the accounts in fabrikam.com except user accounts. Uses the LDAP search syntax.
On Error Resume Next

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000

objCommand.CommandText = _
    ";(!(objectCategory=User));Name;Subtree"  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("Name").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search for All Users in Active Directory
Script About: Scripting Techniques
Demonstration script that returns the names of all the user accounts in Active Directory.
On Error Resume Next

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 

objCommand.CommandText = _
    "SELECT Name FROM 'LDAP://dc=fabrikam,dc=com' WHERE objectCategory='user'"  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("Name").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search for All Users That Have a Phone Number
Script About: Scripting Techniques
Demonstration script that returns the names of all Active Directory users who have a phone number. Uses the LDAP search syntax.
On Error Resume Next

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000

objCommand.CommandText = _
    ";(&(objectCategory=User)" & _
        "(telephoneNumber=*));Name;Subtree"  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("Name").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search for All Users Using an LDAP Query
Script About: Scripting Techniques
Demonstration script that uses the LDAP search syntax to return the names of all the Active Directory user accounts.
On Error Resume Next

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000

objCommand.CommandText = _
    ";(objectCategory=User);Name;Subtree"  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("Name").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search for Attributes in the Global Catalog
Script About: Scripting Techniques
Demonstration script that returns the names of the attributes that are found in the global catalog, and indicates whether those attributes are indexed.
On Error Resume Next

Const IS_INDEXED = 1
Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCommand.CommandText = _
    "SELECT lDAPDisplayName,isMemberOfPartialAttributeSet,searchFlags " _
        & "FROM 'LDAP://CN=Schema,CN=Configuration,DC=fabrikam,DC=com'"_
            & " WHERE objectClass='attributeSchema'"
Set objRecordSet = objCommand.Execute

Do Until objRecordSet.EOF
    WScript.Echo objRecordset.Fields("lDAPDisplayName") 
    If objRecordset.Fields("isMemberOfPartialAttributeSet") Then
        WScript.Echo "In the global catalog."
    End If
    If IS_INDEXED AND objRecordset.Fields("searchFlags") Then
        WScript.Echo "Indexed."
    End If
    Wscript.Echo
    objRecordSet.MoveNext
Loop
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search for Computers Running Windows 2003
Script About: Scripting Techniques
Demonstration script that searches Active Directory for all computers running Windows Server 2003.
On Error Resume Next

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = ("ADsDSOObject")
objConnection.Open "Active Directory Provider"
objCommand.ActiveConnection = objConnection
objCommand.Properties("Page Size") = 1000 
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE  
objCommand.CommandText = _ 
    "SELECT Name, operatingSystemVersion FROM " _   
        & "'LDAP://DC=fabrikam,DC=com'" _ 
            & " WHERE objectClass='computer' AND " _
                &"operatingSystemVersion = '5.2 (3790)'" 
Set objRecordSet = objCommand.Execute 
objRecordSet.MoveFirst 

Do Until objRecordSet.EOF 
    Wscript.Echo "Name: " & objRecordSet.Fields("Name").Value 
    objRecordSet.MoveNext 
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search for Global Security Groups
Script About: Scripting Techniques
Demonstration script that returns the names of all the global security groups in Active Directory.
On Error Resume Next

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 

objCommand.CommandText = _
    "SELECT cn FROM 'LDAP://dc=fabrikam,dc=com' WHERE " _
        & "objectCategory='group' AND " _
            & "groupType= -2147483646 "  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("cn").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search for Multiple Attributes
Script About: Scripting Techniques
Demonstration script that returns multiple attributes from an Active Directory search.
On Error Resume Next

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 

objCommand.CommandText = _
    "SELECT AdsPath,givenName,SN,title,telephoneNumber " _
        & "FROM 'LDAP://dc=fabrikam,dc=com' WHERE " _
            & "objectCategory='user'"  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("ADsPath").Value
    Wscript.Echo objRecordSet.Fields("givenName").Value
    Wscript.Echo objRecordSet.Fields("SN").Value
    Wscript.Echo objRecordSet.Fields("title").Value
    Wscript.Echo _
        objRecordSet.Fields("telephoneNumber").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search for User Accounts That Have Been Disabled
Script About: Scripting Techniques
Demonstration script that returns the names of all disabled user accounts in Active Directory. Uses the LDAP search syntax.
On Error Resume Next

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000

objCommand.CommandText = _
    ";(&(objectCategory=User)" & _
        "(userAccountControl:1.2.840.113556.1.4.803:=2));Name;Subtree"  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("Name").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search for User Phone Numbers Beginning with 425
Script About: Scripting Techniques
Demonstration script that returns all the user accounts with phone numbers in the 425 area code. Uses the LDAP search syntax.
On Error Resume Next

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000

objCommand.CommandText = _
    ";(&(objectCategory=User)" & _
        "(telephoneNumber=425*));Name;Subtree"  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("Name").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search for Users Accounts That are Locked Out
Script About: Scripting Techniques
Demonstration script that returns a list of all locked-out user accounts. Uses the LDAP search syntax.
On Error Resume Next

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000

objCommand.CommandText = _
    ";(&(objectCategory=User)" & _
        "(userAccountControl:1.2.840.113556.1.4.803:=10));Name;Subtree"  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("Name").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search for Users in a Specific Department
Script About: Scripting Techniques
Demonstration script that returns the names of all the users in the Finance Department. Uses the LDAP search syntax.
On Error Resume Next

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000

objCommand.CommandText = _
    ";(&(objectCategory=User)" & _
        "(department=Finance));Name;Subtree"  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("Name").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search for Users in One of Two Departments
Script About: Scripting Techniques
Demonstration script that returns a list of all the users in either the Finance or the Research departments. Uses the LDAP search syntax.
On Error Resume Next

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000

objCommand.CommandText = _
    ";(|(department=Finance)" & _
        "(department=Research));Name;Subtree"  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("Name").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search for Users Not in a Specific Department
Script About: Scripting Techniques
Demonstration script that returns a list of all the users who are not members of the Finance Department. Uses the LDAP search syntax.
On Error Resume Next

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000

objCommand.CommandText = _
    ";(&(objectCategory=User)" & _
        "(!(department=Finance)));Name;Subtree"  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("Name").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search For Users with Non-Expiring Passwords
Script About: Scripting Techniques
Demonstration script that returns a list of all users who have a password that does not expire. Uses the LDAP search syntax.
On Error Resume Next

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000

objCommand.CommandText = _
    ";(&(objectCategory=User)" & _
        "(userAccountControl:1.2.840.113556.1.4.803:=65536));Name;Subtree"  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("Name").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search for Users Without a Phone Number
Script About: Scripting Techniques
Demonstration script that returns a list of all users who do not have a telephone number. Uses the LDAP search syntax.
On Error Resume Next

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000

objCommand.CommandText = _
    ";(&(objectCategory=User)" & _
        "(!(telephoneNumber=*)));Name;Subtree"  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("Name").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Sort a Recordset by User Name
Script About: Scripting Techniques
Demonstration script that returns a list of all the users in the fabrikam.com domain, and then sorts that list alphabetically by name.
On Error Resume Next

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 
objCommand.Properties("Sort on") = "Name"

objCommand.CommandText = _
    "SELECT Name FROM 'LDAP://dc=fabrikam,dc=com' WHERE " _
        & "objectCategory='user'"  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("Name").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Use a Search to Modify Objects
Script About: Scripting Techniques
Demonstration script that returns a list of all the users in the Accounting Department, and then changes their department name to Finance.
On Error Resume Next

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 

objCommand.CommandText = _
    "SELECT ADsPath FROM 'LDAP://dc=fabrikam,dc=com' WHERE " _
        & "objectCategory='user' AND Department='Accounting'"  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    strPath = objRecordSet.Fields("AdsPath").Value
    Set objUser = GetObject(strPath)
    objUser.Department = "Finance"
    objUser.SetInfo
objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Use a Wildcard in a SQL Query
Script About: Scripting Techniques
Demonstration script that uses a wildcard search to return a list of all Active Directory groups whose common name begins with the letters HR.
On Error Resume Next

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 

objCommand.CommandText = _
    "SELECT cn FROM 'LDAP://dc=fabrikam,dc=com' WHERE " _
        & "objectCategory='group' AND cn = 'HR*' "  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("cn").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Use an LDAP OR Filter in a Search
Script About: Scripting Techniques
Demonstration script showing the use of an OR filter in a LDAP query.
On Error Resume Next

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000

objCommand.CommandText = _
    ";(&(objectCategory=User)" & _
        "(|(department=Finance)(department=Research)));Name;Subtree"  
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("Name").Value
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Auto-Generate a File Name
Script About: Scripting Techniques
Demonstration script that uses the FileSystemObject's GetTempName method to generate random file names. Script must be run on the local computer.
Set objFSO = CreateObject("Scripting.FileSystemObject")

For i = 1 to 10
    strTempFile = objFSO.GetTempName
    Wscript.Echo strTempFile
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Create a Text File
Script About: Scripting Techniques
Demonstration script that creates a new, empty text file. Script must be run on the local computer.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("C:\FSO\ScriptLog.txt")
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Create and Auto-Name a Text File
Script About: Scripting Techniques
Demonstration script that uses the FileSystemObject's GetTempName method to generate a file name, and then creates a file by that name.
Set objFSO = CreateObject("Scripting.FileSystemObject")

strPath = "C:\FSO"
strFileName = objFSO.GetTempName
strFullName = objFSO.BuildPath(strPath, strFileName)
Set objFile = objFSO.CreateTextFile(strFullName)
objFile.Close
objFSO.DeleteFile(strFullName)
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Modify the ODBC Default Value to Comma-Delimited When Reading Text Files
Script About: Scripting Techniques
Modifies the registry so that ODBC assumes that text files -- unless otherwise indicated -- are saved in comma-delimited format.
Const HKEY_LOCAL_MACHINE = &H80000002

strComputer = "."
Set objReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ 
    strComputer & "\root\default:StdRegProv")

strKeyPath = "SOFTWARE\Microsoft\Jet\4.0\Engines\Text"
strValueName = "Format"
strValue = "CSVDelimited"
objReg.SetStringValue _
    HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Modify the ODBC Default Value to Tab-Delimited When Reading Text Files
Script About: Scripting Techniques
Modifies the registry so that ODBC assumes that text files -- unless otherwise indicated -- are saved in tab-delimited format.
Const HKEY_LOCAL_MACHINE = &H80000002

strComputer = "."
Set objReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ 
    strComputer & "\root\default:StdRegProv")

strKeyPath = "SOFTWARE\Microsoft\Jet\4.0\Engines\Text"
strValueName = "Format"
strValue = "TabDelimited"
objReg.SetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Read a CSV File Using Database Techniques
Script About: Scripting Techniques
Demonstration script that uses ADO (Active Database Objects) to read a comma-separated-values text file.
On Error Resume Next

Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H0001

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

strPathtoTextFile = "C:\Databases\"

objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=" & strPathtoTextFile & ";" & _
          "Extended Properties=""text;HDR=YES;FMT=Delimited"""

objRecordset.Open "SELECT * FROM PhoneList.csv", _
          objConnection, adOpenStatic, adLockOptimistic, adCmdText

Do Until objRecordset.EOF
    Wscript.Echo "Name: " & objRecordset.Fields.Item("Name")
    Wscript.Echo "Department: " & _
        objRecordset.Fields.Item("Department")
    Wscript.Echo "Extension: " & objRecordset.Fields.Item("Extension")   
    objRecordset.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Read a Fixed-Width Text File Using Database Techniques
Script About: Scripting Techniques
Demonstration script that uses ADO (Active Database Objects) to read a fixed-width text file.
On Error Resume Next

Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H0001

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

strPathtoTextFile = "C:\Databases\"

objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=" & strPathtoTextFile & ";" & _
          "Extended Properties=""text;HDR=YES;FMT=FixedLength"""

objRecordset.Open "SELECT * FROM PhoneList.txt", _
          objConnection, adOpenStatic, adLockOptimistic, adCmdText

Do Until objRecordset.EOF
    Wscript.Echo "Name: " & objRecordset.Fields.Item("FirstName")
    Wscript.Echo "Department: " & objRecordset.Fields.Item("LastName")
    Wscript.Echo "Extension: " & objRecordset.Fields.Item("ID")   
    objRecordset.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Read a Text File Character-by-Character
Script About: Scripting Techniques
Demonstration script that uses the FileSystemObject to read a text file character-by-character, and individually echo those characters to the screen. Script must be run on the local computer.
Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objFile = objFSO.OpenTextFile("C:\FSO\New Text Document.txt", 1)
Do Until objFile.AtEndOfStream
    strCharacters = objFile.Read(1)
    Wscript.Echo strCharacters
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Read a Text File from the Bottom Up
Script About: Scripting Techniques
Demonstration script that uses the FileSystemObject to read a text file, and then displays the text file in inverse order (that is, beginning with the last line in the text file and ending with the first line).
Dim arrFileLines()
i = 0

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\FSO\ScriptLog.txt", 1)

Do Until objFile.AtEndOfStream
     Redim Preserve arrFileLines(i)
     arrFileLines(i) = objFile.ReadLine
     i = i + 1
Loop

objFile.Close

For l = Ubound(arrFileLines) to LBound(arrFileLines) Step -1
    Wscript.Echo arrFileLines(l)
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Read a Text File into an Array
Script About: Scripting Techniques
Demonstration script that uses the VBScript Split command to read a line from a commas-separated values file, and then place the individual items in that line into an array.
Const ForReading = 1

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
    ("c:\scripts\servers and services.txt", ForReading)

Do Until objTextFile.AtEndOfStream
    strNextLine = objTextFile.Readline
    arrServiceList = Split(strNextLine , ",")
    Wscript.Echo "Server name: " & arrServiceList(0)
    For i = 1 to Ubound(arrServiceList)
        Wscript.Echo "Service: " & arrServiceList(i)
    Next
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Verify the Size of a File Before Reading It
Script About: Scripting Techniques
Demonstration script that uses the FileSystemObject to ensure that a text file is not empty before attempting to read it. Script must be run on the local computer.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile("C:\Windows\Netlogon.log")

If objFile.Size > 0 Then
    Set objReadFile = objFSO.OpenTextFile("C:\Windows\Netlogon.log", 1)
    strContents = objReadFile.ReadAll
    Wscript.Echo strContents
    objReadFile.Close
Else
    Wscript.Echo "The file is empty."
End If
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Writing Data to a Text File
Script About: Scripting Techniques
Demonstration script that retrieves the status for all the services installed on a computer, and then saves the service name and status to a text file.
Const ForAppending = 8

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
    ("c:\scripts\service_status.txt", ForAppending, True)

Set objWMIService=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ 
    strComputer & "\root\cimv2")
Set colServices = objWMIService.ExecQuery("Select * from Win32_Service")

For Each objService in colServices    
    objTextFile.WriteLine(objService.DisplayName & vbTab & _
        objService.State)
Next
objTextFile.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Copy Text to the Clipboard
Script About: Scripting Techniques
Sample HTML script for copying text found in a text area named BasicTextArea to the clipboard.
Sub RunScript
    strCopy = BasicTextArea.Value
    document.parentwindow.clipboardData.SetData "text", strCopy
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Create a Timer
Script About: Scripting Techniques
Sample HTML code for adding a timer to a Web page, This timer calls a function named RunScript every 5 seconds (5000 milliseconds).
Sub Window_OnLoad
    iTimerID = window.setInterval("RunScript", 5000, "VBScript")
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Create an Instance of Internet Explorer
Script About: Scripting Techniques
Demonstration script that creates an instance of Internet Explorer, opened to a blank page.
Set objExplorer = WScript.CreateObject("InternetExplorer.Application")

objExplorer.Navigate "about:blank"   
objExplorer.ToolBar = 0
objExplorer.StatusBar = 0
objExplorer.Width=300
objExplorer.Height = 150 
objExplorer.Left = 0
objExplorer.Top = 0
objExplorer.Visible = 1
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Disable a Control
Script About: Scripting Techniques
Sample HTML code that disabled a dropdown list (named Dropdown1) on a Web page or HTA.
Sub RunScript
    DropDown1.Disabled = False
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Display a Confirmation Box
Script About: Scripting Techniques
HTML code that displays a confirmation box on a Web page or HTA and then indicates which button the user clicked.
Sub RunScript
    blnAnswer = window.confirm("Are you sure you want to continue?")
    If blnAnswer Then
        Msgbox "You clicked the OK button"
    Else
        Msgbox "You clicked the Cancel button."
    End If
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Display a Message Box
Script About: Scripting Techniques
Sample HTML function that displays a message box in a Web page or HTA.
Sub RunScript
    Msgbox "Test"
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Display Data in a New Window
Script About: Scripting Techniques
Sample HTML function that displays information in a new Internet Explorer window.
Sub RunScript
    Set objIE = CreateObject("InternetExplorer.Application")
    objIE.Navigate("about:blank")
    objIE.ToolBar = 0
    objIE.StatusBar = 0
    Set objDoc = objIE.Document.Body
    strHTML = "This information is displayed in a separate window."
    objDoc.InnerHTML = strHTML
    objIE.Visible = True
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Display the Print Dialog Box
Script About: Scripting Techniques
Sample HTML function that displays the Print dialog box in a Web page or HTA.
Sub RunScript
    Window.Print()
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List Selected Items in a Multi-select Listbox
Script About: Scripting Techniques
Sample HTML function that lists all the items that were selected in a multi-select listbox.
Sub RunScript
    For i = 0 to (Dropdown1.Options.Length - 1)
        If (Dropdown1.Options(i).Selected) Then
            strComputer = strComputer & Dropdown1.Options(i).Value & vbcrlf
        End If
    Next
    Msgbox strComputer
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List the Value of a Checkbox
Script About: Scripting Techniques
Sample HTML function that indicates whether a checkbox named BasicCheckbox has been checked or not.
Sub RunScript
    If BasicCheckbox.Checked Then
        Msgbox "The checkbox has been checked."
    Else
        Msgbox "The checkbox has not been checked."
    End If
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List the Value of a Dropdown List
Script About: Scripting Techniques
Sample HTML function that reports the value of a dropdown list named Dropwdown1.
Sub RunScript
    Msgbox DropDown1.Value
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List the Value of a Listbox
Script About: Scripting Techniques
Sample HTML function that reports the value of a listbox named Listbox1.
Sub RunScript
    Msgbox Listbox1.Value
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List the Value of a Password Box
Script About: Scripting Techniques
Sample HTML function that reports the value of a password box named PasswordArea.
Sub RunScript
    Msgbox PasswordArea.Value
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List the Value of a Text Box
Script About: Scripting Techniques
Sample HTML function that reports the value of a text box named BasicTextBox.
Sub RunScript
    Msgbox BasicTextBox.Value
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Modify the Cursor Type
Script About: Scripting Techniques
Sample HTML function that changes the Internet Explorer cursor to an hourglass. Other values you can set the cursor to include crosshair; default; hand; and help.
Sub RunScript
    document.body.style.cursor = "wait"
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Modify the Value of a SPAN
Script About: Scripting Techniques
Sample HTML function that changes the value of a SPAN named DataArea.
Sub RunScript
    DataArea.InnerHTML = "The computer did not respond when pinged."
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Modify the Value of a Text Area
Script About: Scripting Techniques
Sample HTML script that changes the text displayed in a multi-line text box.
Sub RunScript
    BasicTextArea.Value = "This information will be placed in the " & _
        "multi-line text box named BasicTextArea."
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Modify the Value of a Tooltip
Script About: Scripting Techniques
Sample HTML function that modifies the tool tip for a button named Run_Button.
Sub RunScript
    Run_Button.Title = "You successfully changed the tool tip."
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Paste Text from the Clipboard
Script About: Scripting Techniques
Sample HTML function that pastes data from the clipboard into a SPAN named DataArea.
Sub RunScript
    DataArea.InnerHTML = document.parentwindow.clipboardData.GetData("text")
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Populate a Listbox Using the Contents of a Text File
Script About: Scripting Techniques
Sample HTML function that opens a text file and adds the contents to a listbox each time a Web page or HTA is loaded.
Sub Window_Onload
    ForReading = 1
    strNewFile = "computers.txt"
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile _
        (strNewFile, ForReading)
    Do Until objFile.AtEndOfStream
        strLine = objFile.ReadLine
        Set objOption = Document.createElement("OPTION")
        objOption.Text = strLine
        objOption.Value = strLine
        AvailableComputers.Add(objOption)
    Loop
    objFile.Close
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Prompt a User for Input
Script About: Scripting Techniques
Sample HTML function that prompts the user for input of some type, and then displays the information entered.
Sub RunScript
    strAnswer = window.prompt("Please enter the domain name.", "fabrikam.com")
    If IsNull(strAnswer) Then
        Msgbox "You clicked the Cancel button"
    Else
        Msgbox "You entered: " & strAnswer
    End If
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Reload a Page
Script About: Scripting Techniques
Sample HTML function that reloads a Web page or HTA.
Sub RunScript
    Location.Reload(True)
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Run a Script Each Time a Page Loads
Script About: Scripting Techniques
Sample HTML function that displays a message box each time a Web page or HTA is loaded.
Sub Window_Onload
    Msgbox "The application has started."
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Save Data to an HTML File
Script About: Scripting Techniques
Sample HTML function that saves the data found in a SPAN named DataArea to a text file named test.htm.
Sub RunScript
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    objFSO.CreateTextFile("test.htm")
    Set objFile = objFSO.OpenTextFile("test.htm", 2)
    objFile.WriteLine DataArea.InnerHTML
    objFile.Close
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Verify That a Radio Button Has Been Selected
Script About: Scripting Techniques
Sample HTML function that indicates whether or not a radio button has been selected.
Sub RunScript
    If UserOption(0).Checked Then
        Msgbox "Option 1 was selected."
    End If
    If UserOption(1).Checked Then
        Msgbox "Option 2 was selected."
    End If
    If UserOption(2).Checked Then
        Msgbox "Option 3 was selected."
    End If
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Create a Permanent Event Consumer
Script About: Scripting Techniques
Creates a permanent event consumer for monitoring changes in service status.
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\default")

Set objConsumerType = objWMIService.get("SMTPEventConsumer")
Set objConsumer = objConsumerType.SpawnInstance_
objConsumer.Name = "Service Monitor Consumer"
objConsumer.Message = "A service has changed state."
objConsumer.SMTPServer = "mailserver.fabrikam.com"
objConsumer.Subject = "Service state change"
objConsumer.ToLine = "administrator@fabrikam.com"
objConsumer.Put_
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Create a Permanent Event Filter
Script About: Scripting Techniques
Creates a permanent event filter for monitoring changes in service status.
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\default")

strFilterQuery = "Select * from __InstanceModificationEvent within 3 " & _
    "where TargetInstance isa 'Win32_Service'"
Set objFilterClass = objWMIService.get("__EventFilter")
Set objFilter = objFilterClass.SpawnInstance_
objFilter.Name = "Service Monitor Filter"
objFilter.QueryLanguage = "wql"
objFilter.Query = strFilterQuery
objFilter.Put_
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List All Abstract Classes in WMI
Script About: Scripting Techniques
Lists all WMI Abstract classes defined in the root\cimv2 namespace.
strComputer = "."
 
Set objWMIService=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ 
    strComputer & "\root\cimv2")

Set colClasses = objWMIService.SubclassesOf()
 
For Each objClass in colClasses
    For Each objClassQualifier In objClass.Qualifiers_
        If LCase(objClassQualifier.Name) = "abstract" Then
            WScript.Echo objClass.Path_.Class & ": " & _
            objClassQualifier.Name & "=" & _
            objClassQualifier.Value
        End If
    Next
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List All Dynamic Classes in WMI
Script About: Scripting Techniques
Lists all WMI Dynamic classes (including Association classes) defined in the root\cimv2 namespace.
strComputer = "."
 
Set objWMIService=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ 
    strComputer & "\root\cimv2")

Set colClasses = objWMIService.SubclassesOf()
 
For Each objClass in colClasses
    For Each objClassQualifier In objClass.Qualifiers_
        If LCase(objClassQualifier.Name) = "dynamic" Then
            WScript.Echo objClass.Path_.Class & ": " & _
            objClassQualifier.Name & "=" & _
            objClassQualifier.Value
        End If
    Next
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List All the Properties and Methods for a WMI Class
Script About: Scripting Techniques
Lists the class qualifiers, properties, property qualifiers, methods, and method qualifiers for a specified WMI class.
strComputer = "."
strNameSpace = "root\cimv2"
strClass = "Win32_Service"
 
Set objClass = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ 
    strComputer & "\" & strNameSpace & ":" & strClass)
 
WScript.Echo strClass & " Class Qualifiers"
WScript.Echo "------------------------------"
i = 1
 
For Each objClassQualifier In objClass.Qualifiers_
    If VarType(objClassQualifier.Value) = (vbVariant + vbArray) Then
        strQualifier = i & ". " & objClassQualifier.Name & " = " & _
            Join(objClassQualifier.Value, ",")
    Else
        strQualifier = i & ". " & objClassQualifier.Name & " = " & _
        objClassQualifier.Value
    End If
    WScript.Echo strQualifier
    strQualifier = ""
    i = i + 1
Next
 
WScript.Echo
WScript.Echo strClass & " Class Properties and Property Qualifiers"
WScript.Echo "------------------------------------------------------"
i = 1 : j = 1
 
For Each objClassProperty In objClass.Properties_
    WScript.Echo i & ". " & objClassProperty.Name
    For Each objPropertyQualifier In objClassProperty.Qualifiers_
        If VarType(objPropertyQualifier.Value) = (vbVariant + vbArray) Then
            strQualifier = i & "." & j & ". " & _
                objPropertyQualifier.Name & " = " & _
            Join(objPropertyQualifier.Value, ",")
        Else
            strQualifier = i & "." & j & ". " & _
                objPropertyQualifier.Name & " = " & _
            objPropertyQualifier.Value
        End If
        WScript.Echo strQualifier
        strQualifier = ""
        j = j + 1
    Next
    WScript.Echo
    i = i + 1 : j = 1
Next
 
WScript.Echo
WScript.Echo strClass & " Class Methods and Method Qualifiers"
WScript.Echo "-------------------------------------------------"
i = 1 : j = 1
 
For Each objClassMethod In objClass.Methods_
    WScript.Echo i & ". " & objClassMethod.Name
    For Each objMethodQualifier In objClassMethod.Qualifiers_
        If VarType(objMethodQualifier.Value) = (vbVariant + vbArray) Then
            strQualifier = i & "." & j & ". " & _
                objMethodQualifier.Name & " = " & _
            Join(objMethodQualifier.Value, ",")
        Else
            strQualifier = i & "." & j & ". " & _
                objMethodQualifier.Name & " = " & _
                    objMethodQualifier.Value
        End If
    WScript.Echo strQualifier
    strQualifier = ""
    j = j + 1
    Next
 
    WScript.Echo
    i = i + 1 : j = 1
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List All the Properties and Methods of the Win32 Classes
Script About: Scripting Techniques
Returns the properties and methods for all the WMI Win32 classes (for example, Win32_Service, Win32_Process, Win32_NTEventLog, etc.).
strComputer = "."
Set objWMIService=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ 
    strComputer & "\root\cimv2")
 
For Each objclass in objWMIService.SubclassesOf()
    intCounter=0
    If Left(objClass.Path_.Class,5) = "Win32" Then
        For Each Qualifier in objClass.Qualifiers_
            If UCase(Trim(Qualifier.Name)) = "ASSOCIATION" Then
                intCounter = 1
            End If
        Next
        If x = 0 Then
            strComputer = "."
            Set objWMIService = GetObject _
                ("winmgmts:{impersonationLevel=impersonate}!\\" & _
                    strComputer & "\root\cimv2")
            Set strClass = objWMIService.Get(objClass.Path_.Class)
            Wscript.Echo "PROPERTIES:"
            For each strItem in strClass.properties_
                Wscript.Echo objClass.Path_.Class & vbTab & strItem.name 
            Next
            Wscript.Echo "METHODS:"
            For Each strItem in strClass.methods_
                Wscript.Echo objClass.Path_.Class & vbTab & strItem.name 
            Next
        End If
    End If
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List All the Properties for a WMI Class
Script About: Scripting Techniques
Lists the properties for a specified WMI class.
strComputer = "."
strNameSpace = "root\cimv2"
strClass = "Win32_Service"
 
Set objClass = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ 
    strComputer & "\" & strNameSpace & ":" & strClass)
 
WScript.Echo strClass & " Class Properties"
WScript.Echo "------------------------------"
 
For Each objClassProperty In objClass.Properties_
    WScript.Echo objClassProperty.Name
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List All the Qualifiers for a WMI Class
Script About: Scripting Techniques
Lists the class qualifiers for a specified WMI class.
strComputer = "."
strNameSpace = "root\cimv2"
strClass = "Win32_Service"
 
Set objClass = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ 
    strComputer & "\" & strNameSpace & ":" & strClass)
 
WScript.Echo strClass & " Class Qualifiers"
WScript.Echo "------------------------------"
 
For Each objClassQualifier In objClass.Qualifiers_
    If VarType(objClassQualifier.Value) = (vbVariant + vbArray) Then
        strQualifier = objClassQualifier.Name & " = " & _
            Join(objClassQualifier.Value, ",")
    Else
        strQualifier = objClassQualifier.Name & " = " & _
            objClassQualifier.Value
    End If
    WScript.Echo strQualifier
    strQualifier = ""
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List All the WMI cimV2 Classes
Script About: Scripting Techniques
Returns a list of all the WMI classes found in the cimv2 namespace.
strComputer = "."
Set objWMIService=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ 
    strComputer & "\root\cimv2")
 
For Each objclass in objWMIService.SubclassesOf()
    Wscript.Echo objClass.Path_.Class
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List All the WMI Methods for a Class
Script About: Scripting Techniques
Lists the methods for a specified WMI class.
strComputer = "."
strNameSpace = "root\cimv2"
strClass = "Win32_Service"
 
Set objClass = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ 
    strComputer & "\" & strNameSpace & ":" & strClass)
 
WScript.Echo strClass & " Class Methods"
WScript.Echo "---------------------------"
 
For Each objClassMethod In objClass.Methods_
    WScript.Echo objClassMethod.Name
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List All the WMI Namespaces
Script About: Scripting Techniques
Lists only those WMI namespaces immediately below the connected namespace.
strComputer = "."
 
Set objWMIService=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ 
    strComputer & "\root")

Set colNameSpaces = objWMIService.InstancesOf("__NAMESPACE")
 
For Each objNameSpace In colNameSpaces
    WScript.Echo objNameSpace.Name
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List All the WMI Providers
Script About: Scripting Techniques
Lists all WMI Providers installed in the root\cimv2 namespace.
strComputer = "."
 
Set objWMIService=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ 
    strComputer & "\root\cimv2")

Set colWin32Providers = objWMIService.InstancesOf("__Win32Provider")
 
For Each objWin32Provider In colWin32Providers
    WScript.Echo objWin32Provider.Name
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List All the WMI Settings
Script About: Scripting Techniques
Returns a list of WMI settings configured on a computer.
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colWMISettings = objWMIService.ExecQuery _
    ("Select * from Win32_WMISetting")

For Each objWMISetting in colWMISettings
    Wscript.Echo "Default namespace: " & _
        objWMISetting.ASPScriptDefaultNamespace
    Wscript.Echo "Backup interval: " & objWMISetting.BackupInterval
    Wscript.Echo "Last backup: " & objWMISetting.BackupLastTime
    Wscript.Echo "Build version: " & objWMISetting.BuildVersion
    Wscript.Echo "Repository directory: " & _
        objWMISetting.DatabaseDirectory
    Wscript.Echo "Enable events: " & objWMISetting.EnableEvents
    Wscript.Echo "High threshold on client objects: " & _
        objWMISetting.HighThresholdOnClientObjects
    Wscript.Echo "High threshold on events: " & _
        objWMISetting.HighThresholdOnEvents
    Wscript.Echo "Installation folder: " & _
        objWMISetting.InstallationDirectory
    Wscript.Echo "Logging folder: " & objWMISetting.LoggingDirectory
    Wscript.Echo "Logging level: " & objWMISetting.LoggingLevel
    Wscript.Echo "Low threshold on client objects: " & _
        objWMISetting.LowThresholdOnClientObjects
    Wscript.Echo "Low threshold on events: " & _
        objWMISetting.LowThresholdOnEvents
    Wscript.Echo "Maximum log file size: " & objWMISetting.MaxLogFileSize
    Wscript.Echo "Maximum wait time on client objects: " & _
        objWMISetting.MaxWaitOnClientObjects
    Wscript.Echo "Maximum wait time on events: " & _
        objWMISetting.MaxWaitOnEvents
    Wscript.Echo "MOF Self-install folder: " & _
        objWMISetting.MofSelfInstallDirectory
    For i = 0 to Ubound(objWMISetting.AutorecoverMofs)
        Wscript.Echo "Autorecover MOF: " & _
            objWMISetting.AutorecoverMofs(i)
    Next
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List All WMI Namespaces
Script About: Scripting Techniques
Lists all WMI namespace on a computer.
strComputer = "."
Call EnumNameSpaces("root")
 
Sub EnumNameSpaces(strNameSpace)
    WScript.Echo strNameSpace
    Set objWMIService=GetObject _
        ("winmgmts:{impersonationLevel=impersonate}\\" & _ 
            strComputer & "\" & strNameSpace)

    Set colNameSpaces = objWMIService.InstancesOf("__NAMESPACE")

    For Each objNameSpace In colNameSpaces
        Call EnumNameSpaces(strNameSpace & "\" & objNameSpace.Name)
    Next
End Sub
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List Computer Hardware
Script About: Scripting Techniques
Returns information about the pointing devices installed on a computer. Used as an example of how to retrieve hardware information using WMI.
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colMice = objWMIService.ExecQuery _
    ("Select * from Win32_PointingDevice")

For Each objMouse in colMice
    Wscript.Echo "Hardware Type: " & objMouse.HardwareType
    Wscript.Echo "Number of Buttons: " & objMouse.NumberOfButtons    
    Wscript.Echo "Status: " & objMouse.Status
    Wscript.Echo "PNP Device ID: " & objMouse.PNPDeviceID
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List System Information
Script About: Scripting Techniques
Uses WMI to retrieve the same data found in the System Information applet.
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colSettings = objWMIService.ExecQuery _
    ("Select * from Win32_OperatingSystem")

For Each objOperatingSystem in colSettings 
    Wscript.Echo "OS Name: " & objOperatingSystem.Name
    Wscript.Echo "Version: " & objOperatingSystem.Version
    Wscript.Echo "Service Pack: " & _
        objOperatingSystem.ServicePackMajorVersion _
            & "." & objOperatingSystem.ServicePackMinorVersion
    Wscript.Echo "OS Manufacturer: " & objOperatingSystem.Manufacturer
    Wscript.Echo "Windows Directory: " & _
        objOperatingSystem.WindowsDirectory
    Wscript.Echo "Locale: " & objOperatingSystem.Locale
    Wscript.Echo "Available Physical Memory: " & _
        objOperatingSystem.FreePhysicalMemory
    Wscript.Echo "Total Virtual Memory: " & _
        objOperatingSystem.TotalVirtualMemorySize
    Wscript.Echo "Available Virtual Memory: " & _
        objOperatingSystem.FreeVirtualMemory
    Wscript.Echo "Size stored in paging files: " & _
        objOperatingSystem.SizeStoredInPagingFiles
Next

Set colSettings = objWMIService.ExecQuery _
    ("Select * from Win32_ComputerSystem")

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

Set colSettings = objWMIService.ExecQuery _
    ("Select * from Win32_Processor")

For Each objProcessor in colSettings 
    Wscript.Echo "System Type: " & objProcessor.Architecture
    Wscript.Echo "Processor: " & objProcessor.Description
Next

Set colSettings = objWMIService.ExecQuery _
    ("Select * from Win32_BIOS")

For Each objBIOS in colSettings 
    Wscript.Echo "BIOS Version: " & objBIOS.Version
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List the Default WMI Namespace
Script About: Scripting Techniques
Retrieves and displays the current WMI "Default namespace for scripting" setting.
strComputer = "."
 
Set objWMIService=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ 
    strComputer & "\root\cimv2")

Set colWMISettings = objWMIService.InstancesOf("Win32_WMISetting")
 
For Each objWMISetting in colWMISettings
    Wscript.Echo "Default namespace for scripting: " & _
    objWMISetting.ASPScriptDefaultNamespace 
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List the Definition of a WMI Class in MOF Format
Script About: Scripting Techniques
Retrieves and displays the textual representation of a WMI class definition in MOF (Managed Object Format) syntax.
strComputer = "."
strNameSpace = "root\cimv2"
strClass = "Win32_Service"
 
Const wbemFlagUseAmendedQualifiers = &h20000
 
Set objClass = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ 
    strComputer & "\" & strNameSpace)

Set objClass = objWMIService.Get(strClass, wbemFlagUseAmendedQualifiers)
strMOF = objClass.GetObjectText_
 
WScript.Echo strMOF
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List WMI Setting Information
Script About: Scripting Techniques
Returns information about how WMI has been configured on a computer.
$strComputer = "."
$objWMIService = GetObject("winmgmts:\\"+ $strComputer + "\root\cimv2")
$colItems = $objWMIService.ExecQuery("Select * from Win32_WMISetting")
For Each $objItem in $colItems
    ? "ASP Script Default Namespace:" + $objItem.ASPScriptDefaultNamespace
    ? "ASP Script Enabled:" + $objItem.ASPScriptEnabled
    For Each $x in $objItem.AutorecoverMofs
        ? "Autorecover Mofs:" + $x
    Next
    ? "AutoStart Win9X:" + $objItem.AutoStartWin9X
    ? "Backup Interval:" + $objItem.BackupInterval
    ? "Backup Last Time:" + $objItem.BackupLastTime
    ? "Build Version:" + $objItem.BuildVersion
    ? "Caption:" + $objItem.Caption
    ? "Database Directory:" + $objItem.DatabaseDirectory
    ? "Database Max Size:" + $objItem.DatabaseMaxSize
    ? "Description:" + $objItem.Description
    ? "Enable Anon Win9x Connections:" + $objItem.EnableAnonWin9xConnections
    ? "Enable Events:" + $objItem.EnableEvents
    ? "EnableS tartup Heap Preallocation:" + $objItem.EnableStartupHeapPreallocation
    ? "High Threshold On Client Objects:" + $objItem.HighThresholdOnClientObjects
    ? "High Threshold On Events:" + $objItem.HighThresholdOnEvents
    ? "Installation Directory:" + $objItem.InstallationDirectory
    ? "Last Startup Heap Preallocation:" + $objItem.LastStartupHeapPreallocation
    ? "Logging Directory:" + $objItem.LoggingDirectory
    ? "Logging Level:" + $objItem.LoggingLevel
    ? "Low Threshold On Client Objects:" + $objItem.LowThresholdOnClientObjects
    ? "Low Threshold On Events:" + $objItem.LowThresholdOnEvents
    ? "Max Log File Size:" + $objItem.MaxLogFileSize
    ? "Max Wait On Client Objects:" + $objItem.MaxWaitOnClientObjects
    ? "Max Wait On Events:" + $objItem.MaxWaitOnEvents
    ? "Mof Self-Install Directory:" + $objItem.MofSelfInstallDirectory
    ? "Setting ID:" + $objItem.SettingID
Next
Platform SupportLanguage Support:Kixtart
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List WMI Setting Information
Script About: Scripting Techniques
Returns information about how WMI has been configured on a computer.
var wbemFlagReturnImmediately = 0x10;
var wbemFlagForwardOnly = 0x20;

   var objWMIService = GetObject("winmgmts:\\\\.\\root\\CIMV2");
   var colItems = objWMIService.ExecQuery("SELECT * FROM Win32_WMISetting", "WQL",
                                          wbemFlagReturnImmediately | wbemFlagForwardOnly);

   var enumItems = new Enumerator(colItems);
   for (; !enumItems.atEnd(); enumItems.moveNext()) {
      var objItem = enumItems.item();

      WScript.Echo("ASP Script Default Namespace: " + objItem.ASPScriptDefaultNamespace);
      WScript.Echo("ASP Script Enabled: " + objItem.ASPScriptEnabled);
      try { WScript.Echo("Autorecover Mofs: " + (objItem.AutorecoverMofs.toArray()).join(",")); }
         catch(e) { WScript.Echo("Autorecover Mofs: null"); }
      WScript.Echo("AutoStart Win9X: " + objItem.AutoStartWin9X);
      WScript.Echo("Backup Interval: " + objItem.BackupInterval);
      WScript.Echo("Backup Last Time: " + objItem.BackupLastTime);
      WScript.Echo("Build Version: " + objItem.BuildVersion);
      WScript.Echo("Caption: " + objItem.Caption);
      WScript.Echo("Database Directory: " + objItem.DatabaseDirectory);
      WScript.Echo("Database Max Size: " + objItem.DatabaseMaxSize);
      WScript.Echo("Description: " + objItem.Description);
      WScript.Echo("Enable Anon Win9x Connections: " + objItem.EnableAnonWin9xConnections);
      WScript.Echo("Enable Events: " + objItem.EnableEvents);
      WScript.Echo("Enable Startup Heap Preallocation: " + objItem.EnableStartupHeapPreallocation);
      WScript.Echo("High Threshold On Client Objects: " + objItem.HighThresholdOnClientObjects);
      WScript.Echo("High Threshold On Events: " + objItem.HighThresholdOnEvents);
      WScript.Echo("Installation Directory: " + objItem.InstallationDirectory);
      WScript.Echo("Last Startup Heap Preallocation: " + objItem.LastStartupHeapPreallocation);
      WScript.Echo("Logging Directory: " + objItem.LoggingDirectory);
      WScript.Echo("Logging Level: " + objItem.LoggingLevel);
      WScript.Echo("Low Threshold On Client Objects: " + objItem.LowThresholdOnClientObjects);
      WScript.Echo("Low Threshold On Events: " + objItem.LowThresholdOnEvents);
      WScript.Echo("Max Log File Size: " + objItem.MaxLogFileSize);
      WScript.Echo("Max Wait On Client Objects: " + objItem.MaxWaitOnClientObjects);
      WScript.Echo("Max Wait On Events: " + objItem.MaxWaitOnEvents);
      WScript.Echo("Mof Self-Install Directory: " + objItem.MofSelfInstallDirectory);
      WScript.Echo("Setting ID: " + objItem.SettingID);
      WScript.Echo();
   }
Platform SupportLanguage Support:Jscript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List WMI Setting Information
Script About: Scripting Techniques
Returns information about how WMI has been configured on a computer.
import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_WMISetting")
for objItem in colItems:
    print "ASP Script Default Namespace: ", objItem.ASPScriptDefaultNamespace
    print "ASP Script Enabled: ", objItem.ASPScriptEnabled
    z = objItem.AutorecoverMofs
    if z is None:
        a = 1
    else:
        for x in z:
            print "Autorecover Mofs: ", x
    print "AutoStart Win9X: ", objItem.AutoStartWin9X
    print "Backup Interval: ", objItem.BackupInterval
    print "Backup Last Time: ", objItem.BackupLastTime
    print "Build Version: ", objItem.BuildVersion
    print "Caption: ", objItem.Caption
    print "Database Directory: ", objItem.DatabaseDirectory
    print "Database Max Size: ", objItem.DatabaseMaxSize
    print "Description: ", objItem.Description
    print "Enable Anon Win9x Connections: ", objItem.EnableAnonWin9xConnections
    print "Enable Events: ", objItem.EnableEvents
    print "Enable Startup Heap Preallocation: ", objItem.EnableStartupHeapPreallocation
    print "High Threshold On Client Objects: ", objItem.HighThresholdOnClientObjects
    print "High Threshold On Events: ", objItem.HighThresholdOnEvents
    print "Installation Directory: ", objItem.InstallationDirectory
    print "Last Startup Heap Preallocation: ", objItem.LastStartupHeapPreallocation
    print "Logging Directory: ", objItem.LoggingDirectory
    print "Logging Level: ", objItem.LoggingLevel
    print "Low Threshold On Client Objects: ", objItem.LowThresholdOnClientObjects
    print "Low Threshold On Events: ", objItem.LowThresholdOnEvents
    print "Max Log File Size: ", objItem.MaxLogFileSize
    print "Max Wait On Client Objects: ", objItem.MaxWaitOnClientObjects
    print "Max Wait On Events: ", objItem.MaxWaitOnEvents
    print "Mof Self-Install Directory: ", objItem.MofSelfInstallDirectory
    print "Setting ID: ", objItem.SettingID
Platform SupportLanguage Support:Python
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List WMI Setting Information
Script About: Scripting Techniques
Returns information about how WMI has been configured on a computer.
strComputer = "."
objWMIService = .OLEObject~GetObject("winmgmts:\\"||strComputer||"\root\CIMV2")
do objItem over objWMIService~ExecQuery("Select * from Win32_WMISetting")
    say "ASP Script Default Namespace:" objItem~ASPScriptDefaultNamespace
    say "ASP Script Enabled:" objItem~ASPScriptEnabled
    z = objItem~AutorecoverMofs
    if .NIL <> z then
        do x over z
            say objProperty.Name ": " x
    end
    say "Auto Start Win9X:" objItem~AutoStartWin9X
    say "Backup Interval:" objItem~BackupInterval
    say "Backup Last Time:" objItem~BackupLastTime
    say "Build Version:" objItem~BuildVersion
    say "Caption:" objItem~Caption
    say "Database Directory:" objItem~DatabaseDirectory
    say "Database Max Size:" objItem~DatabaseMaxSize
    say "Description:" objItem~Description
    say "Enable Anon Win9x Connections:" objItem~EnableAnonWin9xConnections
    say "Enable Events:" objItem~EnableEvents
    say "Enable Startup Heap Preallocation:" objItem~EnableStartupHeapPreallocation
    say "High Threshold On Client Objects:" objItem~HighThresholdOnClientObjects
    say "High Threshold On Events:" objItem~HighThresholdOnEvents
    say "Installation Directory:" objItem~InstallationDirectory
    say "Last Startup Heap Preallocation:" objItem~LastStartupHeapPreallocation
    say "Logging Directory:" objItem~LoggingDirectory
    say "Logging Level:" objItem~LoggingLevel
    say "Low Threshold On Client Objects:" objItem~LowThresholdOnClientObjects
    say "Low Threshold On Events:" objItem~LowThresholdOnEvents
    say "Max Log File Size:" objItem~MaxLogFileSize
    say "Max Wait On Client Objects:" objItem~MaxWaitOnClientObjects
    say "Max Wait On Events:" objItem~MaxWaitOnEvents
    say "Mof Self Install Directory:" objItem~MofSelfInstallDirectory
    say "Setting ID:" objItem~SettingID
end
Platform SupportLanguage Support:Rexx
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Modify the Default WMI Namespace
Script About: Scripting Techniques
Sets the WMI "Default namespace for scripting" setting to "root\cimv2".
strComputer = "."
 
Set objWMIService=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ 
    strComputer & "\root\cimv2")

Set colWMISettings = objWMIService.InstancesOf("Win32_WMISetting")
 
For Each objWMISetting in colWMISettings
    objWMISetting.ASPScriptDefaultNamespace = "root\cimv2"
    objWMISetting.Put_
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Modify WMI Settings
Script About: Scripting Techniques
Configures the WMI backup interval and logging level.
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colWMISettings = objWMIService.ExecQuery _
    ("Select * from Win32_WMISetting")

For Each objWMISetting in colWMISettings
    objWMISetting.BackupInterval = 60
    objWMISetting.LoggingLevel = 2
    objWMISetting.Put_
Next
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Monitor Baseline Performance
Script About: Scripting Techniques
Uses cooked performance counters and the SWbemRefresher object to monitor three performance counters on a computer, and then save that data to a text file.
Const ForAppending = 8

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
  & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

set objRefresher = CreateObject("WbemScripting.Swbemrefresher")
Set objMemory = objRefresher.AddEnum _
  (objWMIService, "Win32_PerfFormattedData_PerfOS_Memory").objectSet
Set objDiskSpace = objRefresher.AddEnum _
  (objWMIService, "Win32_PerfFormattedData_PerfDisk_LogicalDisk").objectSet
Set objQueueLength = objRefresher.AddEnum _
  (objWMIService, "Win32_PerfFormattedData_PerfNet_ServerWorkQueues").objectSet
objRefresher.Refresh

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLogFile = objFSO.OpenTextFile _
  ("c:\scripts\performance.csv", ForAppending, True)

For i = 1 to 10
  For Each intAvailableBytes in objMemory
      objLogFile.Write(intAvailableBytes.AvailableMBytes) & "," 
  Next
  For each intQueueLength in objDiskSpace
      objLogFile.Write(intQueueLength.CurrentDiskQueueLength) & "," 
  Next
  For each intServerQueueLength in objQueueLength
      objLogFile.Write(intServerQueueLength.QueueLength) & ","
  Next
  objLogFile.Write VbCrLf
  Wscript.Sleep 10000
  objRefresher.Refresh
Next
objLogFile.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesNoNoNo
Add a New Record to a Table
Script About: Scripting Techniques
Demonstration script that adds a new record to a database.
Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
    "Provider = Microsoft.Jet.OLEDB.4.0; " & _
        "Data Source = inventory.mdb" 

objRecordSet.Open "SELECT * FROM GeneralProperties" , _
    objConnection, adOpenStatic, adLockOptimistic

objRecordSet.AddNew
objRecordSet("ComputerName") = "atl-ws-01"
objRecordSet("Department") = "Human Resources"
objRecordSet("OSName") = "Microsoft Windows XP Professional"
objRecordSet("OSVersion") = "5.1.2600"
objRecordSet("OSManufacturer") = "Microsoft Corporation"
objRecordSet.Update

objRecordSet.Close
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Clear a Database Table
Script About: Scripting Techniques
Demonstration script that deletes all the records in a table named Hardware from an ADO database with the DSN "Inventory."
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adUseClient = 3
Set objConnection = CreateObject("ADODB.Connection")
Set objRecordset = CreateObject("ADODB.Recordset")
objConnection.Open "DSN=Inventory;"
objRecordset.CursorLocation = adUseClient
objRecordset.Open "Delete * FROM Hardware" , objConnection, _
    adOpenStatic, adLockOptimistic
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Connect to a SQL Server Database
Script About: Scripting Techniques
Demonstration script that connects to a SQL Server database named Northwind on a computer named atl-sql-01.
Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
    "Provider=SQLOLEDB;Data Source=atl-sql-01;" & _
        "Trusted_Connection=Yes;Initial Catalog=Northwind;" & _
             "User ID=fabrikam\kenmyer;Password=34DE6t4G!;"

objRecordSet.Open "SELECT * FROM Customers", _
        objConnection, adOpenStatic, adLockOptimistic

objRecordSet.MoveFirst

Wscript.Echo objRecordSet.RecordCount
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Connect to an ADO Database
Script About: Scripting Techniques
Demonstration script that deletes all the records in a table named Hardware from an ADO database with the DSN "Inventory."
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adUseClient = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordset = CreateObject("ADODB.Recordset")

objConnection.Open "DSN=Inventory;"
objRecordset.CursorLocation = adUseClient
objRecordset.Open "SELECT * FROM Hardware" , objConnection, _
    adOpenStatic, adLockOptimistic
objRecordset.Close
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Create a JET Database
Script About: Scripting Techniques
Demonstration script that creates a new database named New_db.mdb.
Set objConnection = CreateObject("ADOX.Catalog")

objConnection.Create _
    "Provider = Microsoft.Jet.OLEDB.4.0; " & _
        "Data Source = new_db.mdb"
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Create a Table in a JET Database
Script About: Scripting Techniques
Demonstration script that creates a new table in a database named New_db.mdb.
Set objConnection = CreateObject("ADODB.Connection")

objConnection.Open _
    "Provider= Microsoft.Jet.OLEDB.4.0; " & _
        "Data Source=new_db.mdb" 

objConnection.Execute "CREATE TABLE EventTable(" & _
    "EventKey COUNTER ," & _
    "Category TEXT(50) ," & _
    "ComputerName TEXT(50) ," & _
    "EventCode INTEGER ," & _
    "RecordNumber INTEGER ," & _
    "SourceName TEXT(50) ," & _
    "TimeWritten DATETIME ," & _
    "UserName TEXT(50) ," & _
    "EventType TEXT(50) ," & _
    "Logfile TEXT(50) ," & _
    "Message MEMO)" 

objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Delete a Record from a Recordset
Script About: Scripting Techniques
Demonstration script that deletes the record for a computer named WebServer from an ADO database with the DSN "Inventory."
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adUseClient = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordset = CreateObject("ADODB.Recordset")

objConnection.Open "DSN=Inventory;"
objRecordset.CursorLocation = adUseClient
objRecordset.Open "SELECT * FROM Hardware" , objConnection, _
    adOpenStatic, adLockOptimistic
strSearchCriteria = "ComputerName = 'WebServer'"
objRecordSet.Find strSearchCriteria
objRecordset.Delete
objRecordset.Close
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Delete Multiple Records from a Table
Script About: Scripting Techniques
Demonstration script that deletes all records from a database where the Department field is equal to Human Resources.
Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
    "Provider = Microsoft.Jet.OLEDB.4.0; " & _
        "Data Source = inventory.mdb" 

objRecordSet.Open "DELETE * FROM GeneralProperties WHERE " & _
    "Department = 'Human Resources'", _
        objConnection, adOpenStatic, adLockOptimistic

objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List Basic Statistics Derived from a Recordset
Script About: Scripting Techniques
Demonstration script that lists the different operating systems found in a database, as well as the number of computers running each operating system.
Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
    "Provider = Microsoft.Jet.OLEDB.4.0; " & _
        "Data Source = inventory.mdb" 

objRecordSet.Open "SELECT OSName, Count(OSName) AS CountOfOSName" & _
   " FROM GeneralProperties GROUP BY OSName ORDER BY Count(OSName) DESC", _
        objConnection, adOpenStatic, adLockOptimistic

objRecordSet.MoveFirst

Do Until objRecordset.EOF
    Wscript.Echo objRecordset.Fields.Item("OSName") & _
        vbTab & objRecordset.Fields.Item("CountOfOSName")
    objRecordset.MoveNext
Loop

objRecordSet.Close
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List the Number of Records in a Recordset
Script About: Scripting Techniques
Demonstration script that returns the number of records in a recordset.
Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
    "Provider = Microsoft.Jet.OLEDB.4.0; " & _
        "Data Source = eventlogs.mdb" 

objRecordSet.Open "SELECT * FROM EventTable" , _
    objConnection, adOpenStatic, adLockOptimistic

objRecordSet.MoveFirst

Wscript.Echo "Number of records: " & objRecordset.RecordCount

objRecordSet.Close
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List the Top 25 Records in a Recordset
Script About: Scripting Techniques
Demonstration script that queries a database for the 25 computers with the most physical memory.
Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
    "Provider = Microsoft.Jet.OLEDB.4.0; " & _
        "Data Source = inventory.mdb" 

objRecordSet.Open "SELECT TOP 25 * FROM GeneralProperties " & _
    "ORDER BY TotalPhysicalMemory DESC", _
        objConnection, adOpenStatic, adLockOptimistic

objRecordSet.MoveFirst

Do Until objRecordset.EOF
    Wscript.Echo objRecordset.Fields.Item("ComputerName") & _
        vbTab & objRecordset.Fields.Item("TotalPhysicalMemory")
    objRecordset.MoveNext
Loop

objRecordSet.Close
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
List Unique Records in a Recordset
Script About: Scripting Techniques
Demonstration script that returns the unique operating systems found in a database.
Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
    "Provider = Microsoft.Jet.OLEDB.4.0; " & _
        "Data Source = inventory.mdb" 

objRecordSet.Open "SELECT DISTINCT OSName FROM " & _
    "GeneralProperties ORDER BY OSName", _
        objConnection, adOpenStatic, adLockOptimistic

objRecordSet.MoveFirst

Do Until objRecordset.EOF
    Wscript.Echo objRecordset.Fields.Item("OSName")
    objRecordset.MoveNext
Loop

objRecordSet.Close
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Open a Database Using a DSN
Script About: Scripting Techniques
Demonstration script that uses a DSN to open a database named Northwind.
Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
    "Northwind;fabrikam\kenmyer;34ghfn&!j"

objRecordSet.Open "SELECT * FROM Customers", _
        objConnection, adOpenStatic, adLockOptimistic

objRecordSet.MoveFirst

Wscript.Echo objRecordSet.RecordCount
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Open Two Recordsets
Script About: Scripting Techniques
Demonstration script that works with two separate recordsets.
Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")
Set objRecordSet2 = CreateObject("ADODB.Recordset")

objConnection.Open _
    "Provider= Microsoft.Jet.OLEDB.4.0; " & _
        "Data Source=inventory.mdb" 

objRecordSet.Open "SELECT * FROM GeneralProperties Where ComputerName = 'Computer1'", _
        objConnection, adOpenStatic, adLockOptimistic

objRecordSet.MoveFirst


objRecordSet2.Open "SELECT * FROM Storage Where ComputerName = 'Computer1'", _
        objConnection, adOpenStatic, adLockOptimistic

objRecordSet2.MoveFirst

Do Until objRecordset.EOF
    Wscript.Echo objRecordset.Fields.Item("ComputerName")
    Wscript.Echo objRecordset.Fields.Item("OSName")
    objRecordSet.MoveNext
Loop

Do Until objRecordset2.EOF
    Wscript.Echo objRecordset2.Fields.Item("DriveName"), _
        objRecordset2.Fields.Item("DriveDescription")
    objRecordSet2.MoveNext
Loop

objRecordSet.Close
objRecordSet2.Close
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Save a Recordset in XML format
Script About: Scripting Techniques
Demonstration script that retrieves data from a database and then saves that data in XML format.
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adPersistXML = 1

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
    "Provider= Microsoft.Jet.OLEDB.4.0; " & _
        "Data Source=eventlogs.mdb" 
objRecordSet.Open "SELECT * FROM EventTable" , _
    objConnection, adOpenStatic, adLockOptimistic

objRecordSet.MoveFirst 

objRecordSet.Save "output.xml", adPersistXML

objRecordSet.Close
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search a Database Using a LIKE Query
Script About: Scripting Techniques
Demonstration script that searches a database for all records where the Message field contains the word PowerPoint.
Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
    "Provider = Microsoft.Jet.OLEDB.4.0; " & _
        "Data Source = eventlogs.mdb" 

objRecordSet.Open "SELECT * FROM EventTable WHERE " & _
    "Message Like '%PowerPoint%'", _
        objConnection, adOpenStatic, adLockOptimistic

objRecordSet.MoveFirst

Wscript.Echo "Number of records: " & objRecordset.RecordCount

objRecordSet.Close
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search a Database Using Numeric Criteria
Script About: Scripting Techniques
Demonstration script that searches a database for all records where the event code is equal to the numeric value 1054.
Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
    "Provider = Microsoft.Jet.OLEDB.4.0; " & _
        "Data Source = eventlogs.mdb" 

objRecordSet.Open "SELECT * FROM EventTable " & _
    "WHERE EventCode = 1054", _
        objConnection, adOpenStatic, adLockOptimistic

objRecordSet.MoveFirst

Wscript.Echo "Number of records: " & objRecordset.RecordCount

objRecordSet.Close
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search a Database Using Variable Criteria
Script About: Scripting Techniques
Demonstration script that searches a database for all records where the TimeWritten field is equal to the value of the variable dtmDate.
Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
    "Provider= Microsoft.Jet.OLEDB.4.0; " & _
        "Data Source=eventlogs.mdb" 

dtmDate = "#1/7/2004#"

objRecordSet.Open "SELECT * FROM EventTable Where TimeWritten = " & dtmDate, objconnection, adOpenStatic, adLockOptimistic

objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordset.Fields.Item("EventCode") & vbTab _
        & objRecordset.Fields.Item("Logfile")
    objRecordSet.MoveNext
Loop
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Search for a Record in a Recordset
Script About: Scripting Techniques
Searches an ADO database with a DSN of "Inventory" looking for a specific computer record.
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adUseClient = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordset = CreateObject("ADODB.Recordset")

objConnection.Open "DSN=Inventory;"
objRecordset.CursorLocation = adUseClient
objRecordset.Open "SELECT * FROM Hardware" , objConnection, _
    adOpenStatic, adLockOptimistic
strSearchCriteria = "ComputerName = 'WebServer'"
objRecordSet.Find strSearchCriteria

If objRecordset.EOF Then 
    Wscript.Echo "Record cannot be found."
Else
    Wscript.Echo "Record found."
End If

objRecordset.Close
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Searching a Database Using String Criteria
Script About: Scripting Techniques
Demonstration script that searches a database for all records where the Type field is equal to Error.
Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
    "Provider = Microsoft.Jet.OLEDB.4.0; " & _
        "Data Source = eventlogs.mdb" 

objRecordSet.Open "SELECT * FROM EventTable " & _
    "WHERE Type = 'Error'", objConnection, adOpenStatic, _
         adLockOptimistic

objRecordSet.MoveFirst

Wscript.Echo "Number of records: " & objRecordset.RecordCount

objRecordSet.Close
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Sort a Recordset
Script About: Scripting Techniques
Demonstration script that sorts a recordset (in ascending order) on the EventCode field.
Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
    "Provider = Microsoft.Jet.OLEDB.4.0; " & _
        "Data Source = eventlogs.mdb" 

objRecordSet.Open "SELECT * FROM EventTable " & _
    "ORDER BY EventCode ASC", _
        objConnection, adOpenStatic, adLockOptimistic

objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields.Item("EventCode"), objRecordSet.Fields.Item("Logfile")
    objRecordSet.MoveNext
Loop

objRecordSet.Close
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Sort a Recordset on Multiple Fields
Script About: Scripting Techniques
Demonstration script that sorts a recordset on two fields: first by EventCode (in ascending order), and then by Logfile (in descending order).
Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
    "Provider = Microsoft.Jet.OLEDB.4.0; " & _
        "Data Source = eventlogs.mdb" 

objRecordSet.Open "SELECT * FROM EventTable " & _
    "ORDER BY EventCode ASC, Logfile DESC", _
        objConnection, adOpenStatic, adLockOptimistic

objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields.Item("EventCode"), objRecordSet.Fields.Item("Logfile")
    objRecordSet.MoveNext
Loop

objRecordSet.Close
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Update a Record in a Recordset
Script About: Scripting Techniques
Demonstration script that updates sound card information for a computer named Webserver.
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adUseClient = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordset = CreateObject("ADODB.Recordset")

objConnection.Open "DSN=Inventory;"
objRecordset.CursorLocation = adUseClient
objRecordset.Open "SELECT * FROM Hardware" , objConnection, _
    adOpenStatic, adLockOptimistic
strSearchCriteria = "ComputerName = 'WebServer'"
objRecordSet.Find strSearchCriteria

Set colSoundCards = GetObject("winmgmts:").ExecQuery _
    ("Select * from Win32_SoundDevice")

For Each objSoundCard in colSoundCards
    objRecordset("ComputerName") = objSoundCard.SystemName
    objRecordset("Manufacturer") = objSoundCard.Manufacturer
    objRecordset("ProductName") = objSoundCard.ProductName
    objRecordset.Update
Next

objRecordset.Close
objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes
Update Multiple Records in a Recordset
Script About: Scripting Techniques
Demonstration script that sets the value of the Department field to Accounting for all the records in a table.
Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
    "Provider = Microsoft.Jet.OLEDB.4.0; " & _
        "Data Source = inventory.mdb" 

objRecordSet.Open "UPDATE GeneralProperties SET " & _
    "Department = 'Accounting'", _
        objConnection, adOpenStatic, adLockOptimistic

objConnection.Close
Platform SupportLanguage Support:VBScript
Win2003WinXPWin2000WinNTWin98
YesYesYesYesYes