System Administration Scripting Guide
Script Repository

Version 1.0, May 2002

The scripts included in this help file are likely to appear in the forthcoming System Administration Scripting Guide, which will ship as part of the Windows .NET Server Resource Kit. In the Scripting Guide itself, each script will be explained in step-by-step fashion, and instructional material will help you learn how to modify these scripts to suit your unique individual needs. In addition, the book will also teach you how to write your own scripts using VBScript, WMI, ADSI, and other Microsoft Scripting technologies.

Most of the scripts are designed to run with either Windows 2000, Windows XP, or Windows .NET Server. Scripts that are not designed to run on all these platforms include a brief note indicating which versions of Windows are required.

To use the scripts, copy the appropriate script code, paste it into Notepad or another text editor, and save the file with a .vbs file extension.

For more information about these scripts or about the book, contact the Scripting Guide team at scripter@microsoft.com

A Note About the WMI Scripts

Most of the WMI scripts in this repository create a variable named strComputer, and then set the value of that variable to "." Thus, the scripts generally include this line:

strComputer = "."

This causes the script to run against the local computer. This is due to the way that the script has been composed, and the fact that WMI views a computer named "." as being the local computer. If you want to run the script against a remote computer, simply replace the "." with the name of the remote computer, surrounded by double quotation marks. For example, this line of code runs the script against a remote computer named PrintServer1:

strComputer = "PrintServer1"

This is the only change you need to make in order to run the WMI scripts against a remote computer. Bear in mind, however, that you will need to have administrative rights on the remote computer in order for the script to succeed. In addition, WMI must be installed both on the local computer and on the remote computer.


Disclaimer

System Administration Scripting Guide
Disclaimer

The SOFTWARE supplied in this download site is not supported under any Microsoft standard support program or service. You can, however, report issues and bugs by sending e-mail to scripter@microsoft.com. Microsoft will, at its sole discretion, address issues and bugs reported in this manner, and responses are not guaranteed.

The SOFTWARE (including instructions for its use and all printed and online documentation) is provided AS IS without warranty of any kind. Microsoft further disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the SOFTWARE and documentation remains with you.

In no event shall Microsoft, its authors, or anyone else involved in the creation, production, or delivery of the SOFTWARE be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the SOFTWARE or documentation, even if Microsoft has been advised of the possibility of such damages.

Important

These scripts have not been localized: they are written and tested in English only. Using these scripts with a different language version of Windows might produce unpredictable results.


Activate Windows Offline

Description
Uses the offline method to activate Windows. Requires Windows XP or Windows .NET Server, and a valid activation number.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colWindowsProducts = objWMIService.ExecQuery _
    ("Select * from Win32_WindowsProductActivation")
For Each objWindowsProduct in colWindowsProducts
    ObjWindowsProduct.ActivateOffline("1234-1234")
Next

The System Administration Scripting Guide, part of the Windows .NET Server Resource Kit. For more information, contact scripter@microsoft.com.


Activate Windows Online

Description
Uses the online method to activate Windows. Requires Windows XP or Windows .NET Server, and an active Internet connection.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colWindowsProducts = objWMIService.ExecQuery _
    ("Select * from Win32_WindowsProductActivation")
For Each objWindowsProduct in colWindowsProducts
    ObjWindowsProduct.ActivateOnline()
Next


Change Computer Account Attributes

Description
Demonstration script that changes the location attribute for a computer account in Active Directory.

Script Code

Set objComputer = GetObject _
    ("LDAP://CN=atl-dc-01,CN=Computers,DC=fabrikam,DC=com")
objComputer.Put "Location" , "Building 37, Floor 2, Room 2133"
objComputer.SetInfo


Configure System Startup Delay

Description
Configures a computer to wait 10 seconds (instead of the default 30 seconds) before automatically loading the default operating system upon startup.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colStartupCommands = objWMIService.ExecQuery _
    ("Select * from Win32_ComputerSystem")
For Each objStartupCommand in colStartupCommands
    objStartupCommand.SystemStartupDelay = 10
    objStartupCommand.Put_


Configure WMI Settings

Description
Configures WMI backup interval and logging level.

Script Code

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_


Create a Computer Account

Description
Creates and enables a computer account in Active Directory, which must be used by an Administrator when adding a workstation to the domain.

Script Code

strComputer = "atl-pro-001"

Const ADS_UF_PASSWD_NOTREQD            = &h0020
Const ADS_UF_WORKSTATION_TRUST_ACCOUNT = &h1000

Set objRootDSE = GetObject("LDAP://rootDSE")
Set objContainer = GetObject("LDAP://cn=Computers," & _
                             objRootDSE.Get("defaultNamingContext"))

Set objComputer = objContainer.Create("Computer", "cn=" & strComputer)
objComputer.Put "sAMAccountName", strComputer & "$"
objComputer.Put "userAccountControl", _
                ADS_UF_PASSWD_NOTREQD Or ADS_UF_WORKSTATION_TRUST_ACCOUNT
objComputer.SetInfo


Create a Computer Account For a User

Description
Creates and enables a computer account in Active Directory, which a specific, authenticated user can use to add his or her workstation to the domain.

Script Code

Option Explicit

Dim strComputer, strComputerUser
Dim objRootDSE, objContainer, objComputer
Dim objSecurityDescriptor, objDACL
Dim objACE1, objACE2, objACE3, objACE4, objACE5
Dim objACE6, objACE7, objACE8, objACE9

strComputer = "atl-pro-002"
strComputerUser = "fabrikam\lewjudy"

' ADS_USER_FLAG_ENUM
Const ADS_UF_PASSWD_NOTREQD            = &h0020
Const ADS_UF_WORKSTATION_TRUST_ACCOUNT = &h1000

' ADS_ACETYPE_ENUM
Const ADS_ACETYPE_ACCESS_ALLOWED        = &h0
Const ADS_ACETYPE_ACCESS_ALLOWED_OBJECT = &h5

' ADS_FLAGTYPE_ENUM
Const ADS_FLAG_OBJECT_TYPE_PRESENT = &h1

' ADS_RIGHTS_ENUM
Const ADS_RIGHT_GENERIC_READ      = &h80000000
Const ADS_RIGHT_DS_SELF           = &h8
Const ADS_RIGHT_DS_WRITE_PROP     = &h20
Const ADS_RIGHT_DS_CONTROL_ACCESS = &h100

'controlAccessRight rightsGuid values
Const ALLOWED_TO_AUTHENTICATE    = "{68B1D179-0D15-4d4f-AB71-46152E79A7BC}"
Const RECEIVE_AS                 = "{AB721A56-1E2f-11D0-9819-00AA0040529B}"
Const SEND_AS                    = "{AB721A54-1E2f-11D0-9819-00AA0040529B}"
Const USER_CHANGE_PASSWORD       = "{AB721A53-1E2f-11D0-9819-00AA0040529b}"
Const USER_FORCE_CHANGE_PASSWORD = "{00299570-246D-11D0-A768-00AA006E0529}"
Const USER_ACCOUNT_RESTRICTIONS  = "{4C164200-20C0-11D0-A768-00AA006E0529}"
Const VALIDATED_DNS_HOST_NAME    = "{72E39547-7B18-11D1-ADEF-00C04FD8D5CD}"
Const VALIDATED_SPN              = "{F3A64788-5306-11D1-A9C5-0000F80367C1}"

Set objRootDSE = GetObject("LDAP://rootDSE")
Set objContainer = GetObject("LDAP://cn=Computers," & _
                             objRootDSE.Get("defaultNamingContext"))

Set objComputer = objContainer.Create("Computer", "cn=" & strComputer)
objComputer.Put "sAMAccountName", strComputer & "$"
objComputer.Put "userAccountControl", _
                ADS_UF_PASSWD_NOTREQD Or ADS_UF_WORKSTATION_TRUST_ACCOUNT
objComputer.SetInfo

Set objSecurityDescriptor = objComputer.Get("ntSecurityDescriptor")
Set objDACL = objSecurityDescriptor.DiscretionaryAcl

Set objACE1 = CreateObject("AccessControlEntry")
objACE1.Trustee    = strComputerUser
objACE1.AccessMask = ADS_RIGHT_GENERIC_READ
objACE1.AceFlags   = 0
objACE1.AceType    = ADS_ACETYPE_ACCESS_ALLOWED

' objACE2 through objACE6: Extended Rights
Set objACE2 = CreateObject("AccessControlEntry")
objACE2.Trustee    = strComputerUser
objACE2.AccessMask = ADS_RIGHT_DS_CONTROL_ACCESS
objACE2.AceFlags   = 0
objACE2.AceType    = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT
objACE2.Flags      = ADS_FLAG_OBJECT_TYPE_PRESENT
objACE2.ObjectType = ALLOWED_TO_AUTHENTICATE

Set objACE3 = CreateObject("AccessControlEntry")
objACE3.Trustee    = strComputerUser
objACE3.AccessMask = ADS_RIGHT_DS_CONTROL_ACCESS
objACE3.AceFlags   = 0
objACE3.AceType    = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT
objACE3.Flags      = ADS_FLAG_OBJECT_TYPE_PRESENT
objACE3.ObjectType = RECEIVE_AS

Set objACE4 = CreateObject("AccessControlEntry")
objACE4.Trustee    = strComputerUser
objACE4.AccessMask = ADS_RIGHT_DS_CONTROL_ACCESS
objACE4.AceFlags   = 0
objACE4.AceType    = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT
objACE4.Flags      = ADS_FLAG_OBJECT_TYPE_PRESENT
objACE4.ObjectType = SEND_AS

Set objACE5 = CreateObject("AccessControlEntry")
objACE5.Trustee    = strComputerUser
objACE5.AccessMask = ADS_RIGHT_DS_CONTROL_ACCESS
objACE5.AceFlags   = 0
objACE5.AceType    = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT
objACE5.Flags      = ADS_FLAG_OBJECT_TYPE_PRESENT
objACE5.ObjectType = USER_CHANGE_PASSWORD

Set objACE6 = CreateObject("AccessControlEntry")
objACE6.Trustee    = strComputerUser
objACE6.AccessMask = ADS_RIGHT_DS_CONTROL_ACCESS
objACE6.AceFlags   = 0
objACE6.AceType    = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT
objACE6.Flags      = ADS_FLAG_OBJECT_TYPE_PRESENT
objACE6.ObjectType = USER_FORCE_CHANGE_PASSWORD

' objACE7: Property Sets
Set objACE7 = CreateObject("AccessControlEntry")
objACE7.Trustee    = strComputerUser
objACE7.AccessMask = ADS_RIGHT_DS_WRITE_PROP
objACE7.AceFlags   = 0
objACE7.AceType    = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT
objACE7.Flags      = ADS_FLAG_OBJECT_TYPE_PRESENT
objACE7.ObjectType = USER_ACCOUNT_RESTRICTIONS

' objACE8 and objACE9: Validated Rights
Set objACE8 = CreateObject("AccessControlEntry")
objACE8.Trustee    = strComputerUser
objACE8.AccessMask = ADS_RIGHT_DS_SELF
objACE8.AceFlags   = 0
objACE8.AceType    = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT
objACE8.Flags      = ADS_FLAG_OBJECT_TYPE_PRESENT
objACE8.ObjectType = VALIDATED_DNS_HOST_NAME

Set objACE9 = CreateObject("AccessControlEntry")
objACE9.Trustee    = strComputerUser
objACE9.AccessMask = ADS_RIGHT_DS_SELF
objACE9.AceFlags   = 0
objACE9.AceType    = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT
objACE9.Flags      = ADS_FLAG_OBJECT_TYPE_PRESENT
objACE9.ObjectType = VALIDATED_SPN

objDACL.AddAce objACE1
objDACL.AddAce objACE2
objDACL.AddAce objACE3
objDACL.AddAce objACE4
objDACL.AddAce objACE5
objDACL.AddAce objACE6
objDACL.AddAce objACE7
objDACL.AddAce objACE8
objDACL.AddAce objACE9

objSecurityDescriptor.DiscretionaryAcl = objDACL
objComputer.Put "ntSecurityDescriptor", objSecurityDescriptor
objComputer.SetInfo


Delete a Computer Account

Description
Deletes an individual computer account in Active Directory.

Script Code

strComputer = "atl-pro-040"
set objComputer = GetObject("LDAP://CN=" & strComputer & _
                            ",CN=Computers,DC=fabrikam,DC=com")
objComputer.DeleteObject (0)


Disable a Global Catalog Server

Description
Disables the global catalog service on a domain controller.

Script Code

strComputer = "atl-dc-01"

Const NTDSDSA_OPT_IS_GC = 1

Set objRootDSE = GetObject("LDAP://" & strComputer & "/rootDSE")
strDsServiceDN = objRootDSE.Get("dsServiceName")
Set objDsRoot  = GetObject("LDAP://" & strComputer & "/" & strDsServiceDN)
intOptions = objDsRoot.Get("options")

If intOptions And NTDSDSA_OPT_IS_GC Then
    objDsRoot.Put "options", intOptions Xor NTDSDSA_OPT_IS_GC
    objDsRoot.Setinfo
End If


Enable a Global Catalog Server

Description
Enables the global catalog service on a domain controller.

Script Code

strComputer = "atl-dc-01"

Const NTDSDSA_OPT_IS_GC = 1

Set objRootDSE = GetObject("LDAP://" & strComputer & "/RootDSE")
strDsServiceDN = objRootDSE.Get("dsServiceName")
Set objDsRoot  = GetObject("LDAP://" & strComputer & "/" & strDsServiceDN)
intOptions = objDsRoot.Get("options")

If (intOptions And NTDSDSA_OPT_IS_GC) = FALSE Then
    objDsRoot.Put "options" , intOptions Or NTDSDSA_OPT_IS_GC
    objDsRoot.Setinfo
End If


Enumerate Computer Account Attributes

Description
Demonstration script that retrieves the location and description attributes for a computer account in Active Directory.

Script Code

On Error Resume Next
Set objComputer = GetObject _
    ("LDAP://CN=atl-dc-01,CN=Computers,DC=fabrikam,DC=com")
objProperty = objComputer.Get("Location")
If IsNull(objProperty) Then
    Wscript.Echo "The location has not been set for this computer."
Else
    Wscript.Echo "Location: " & objProperty
    objProperty = Null
End If
objProperty = objComputer.Get("Description")
If IsNull(objProperty) Then
    Wscript.Echo "The description has not been set for this computer."
Else
    Wscript.Echo "Description: " & objProperty
    objProperty = Null
End If


Enumerate Computer Accounts in Active Directory

Description
Returns the name and location for all the computer accounts in Active Directory.

Script Code

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 Name, Location from 'LDAP://DC=fabrikam,DC=com' " _
        & "where objectClass='computer'"
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Timeout") = 30
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCommand.Properties("Cache Results") = False
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
Do Until objRecordSet.EOF
    Wscript.Echo "Computer Name: " & objRecordSet.Fields("Name").Value
    Wscript.Echo "Location: " & objRecordSet.Fields("Location").Value
    objRecordSet.MoveNext
Loop


Enumerate Computer Startup Commands

Description
Enumerates all startup commands on a computer, including those found in the Startup folder and those found in the Registry.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colStartupCommands = objWMIService.ExecQuery _
    ("Select * from Win32_StartupCommand")
For Each objStartupCommand in colStartupCommands
    Wscript.Echo "Command: " & objStartupCommand.Command
    Wscript.Echo "Description: " & objStartupCommand.Description
    Wscript.Echo "Location: " & objStartupCommand.Location
    Wscript.Echo "Name: " & objStartupCommand.Name
    Wscript.Echo "SettingID: " & objStartupCommand.SettingID
    Wscript.Echo "User: " & objStartupCommand.User


Enumerate Computer Startup Options

Description
Returns a list of startup options for a computer, including the startup delay time and other information found in Boot.ini.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colStartupCommands = objWMIService.ExecQuery _
    ("Select * from Win32_ComputerSystem")
For Each objStartupCommand in colStartupCommands
    Wscript.Echo "Reset Boot Enabled: " & _
        objStartupCommand.AutomaticResetBootOption
    Wscript.Echo "Reset Boot Possible: " & _
        objStartupCommand.AutomaticResetCapability
    Wscript.Echo "Boot State: " & objStartupCommand.BootupState
    Wscript.Echo "Startup Delay: " & objStartupCommand.SystemStartupDelay
    For i = 0 to Ubound(objStartupCommand.SystemStartupOptions)
        Wscript.Echo "Startup Options: " & _
            objStartupCommand.SystemStartupOptions(i)
    Next
    Wscript.Echo "Startup Setting: " & _
        objStartupCommand.SystemStartupSetting


Enumerate Installed Hot Fixes

Description
Returns a list of all the hot fixes installed on a computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colQuickFixes = objWMIService.ExecQuery _
    ("Select * from Win32_QuickFixEngineering")
For Each objQuickFix in colQuickFixes
    Wscript.Echo "Computer: " & objQuickFix.CSName
    Wscript.Echo "Description: " & objQuickFix.Description
    Wscript.Echo "Hot Fix ID: " & objQuickFix.HotFixID
    Wscript.Echo "Installation Date: " & objQuickFix.InstallDate
    Wscript.Echo "Installed By: " & objQuickFix.InstalledBy


Enumerate Installed Software

Description
Returns a list of software that was installed on a computer using Windows Installer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.CreateTextFile("c:\scripts\software.tsv", True)
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colSoftware = objWMIService.ExecQuery _
    ("Select * from Win32_Product")
objTextFile.WriteLine "Caption" & vbtab & _
    "Description" & vbtab & "Identifying Number" & vbtab & _
    "Install Date" & vbtab & "Install Location" & vbtab & _
    "Install State" & vbtab & "Name" & vbtab & _
    "Package Cache" & vbtab & "SKU Number" & vbtab & "Vendor" & vbtab _
        & "Version"
For Each objSoftware in colSoftware
    objTextFile.WriteLine objSoftware.Caption & vbtab & _
    objSoftware.Description & vbtab & _
    objSoftware.IdentifyingNumber & vbtab & _
    objSoftware.InstallDate2 & vbtab & _
    objSoftware.InstallLocation & vbtab & _
    objSoftware.InstallState & vbtab & _
    objSoftware.Name & vbtab & _
    objSoftware.PackageCache & vbtab & _
    objSoftware.SKUNumber & vbtab & _
    objSoftware.Vendor & vbtab & _
    objSoftware.Version
objTextFile.Close


Enumerate Installed Software Features

Description
Returns a list of features for all the software that was installed on a computer using Windows Installer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFeatures = objWMIService.ExecQuery _
    ("Select * from Win32_SoftwareFeature")
For each objFeature in colfeatures
    Wscript.Echo "Accesses: " & objFeature.Accesses
    Wscript.Echo "Attributes: " & objFeature.Attributes
    Wscript.Echo "Caption: " & objFeature.Caption
    Wscript.Echo "Description: " & objFeature.Description
    Wscript.Echo "Identifying Number: " & objFeature.IdentifyingNumber
    Wscript.Echo "Install Date: " & objFeature.InstallDate
    Wscript.Echo "Install State: " & objFeature.InstallState
    Wscript.Echo "LastUse: " & objFeature.LastUse
    Wscript.Echo "Name: " & objFeature.Name
    Wscript.Echo "ProductName: " & objFeature.ProductName
    Wscript.Echo "Vendor: " & objFeature.Vendor
    Wscript.Echo "Version: " & objFeature.Version


Enumerate Recovery Configuration Options

Description
Returns a list of settings that indicate the action to be taken by a computer should a stop event (blue screen) occur.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colRecoveryOptions = objWMIService.ExecQuery _
    ("Select * from Win32_OSRecoveryConfiguration")
For Each objOption in colRecoveryOptions
    Wscript.Echo "Auto reboot: " & objOption.AutoReboot
    Wscript.Echo "Debug File Path: " & objOption.DebugFilePath
    Wscript.Echo "Debug Info Type: " & objOption.DebugInfoType
    Wscript.Echo "Kernel Dump Only: " & objOption.KernelDumpOnly
    Wscript.Echo "Name: " & objOption.Name
    Wscript.Echo "Overwrite Existing Debug File: " & _
        objOption.OverwriteExistingDebugFile
    Wscript.Echo "Send Administrative Alert: " & objOption.SendAdminAlert
    Wscript.Echo "Write Debug Information: " & objOption.WriteDebugInfo
    Wscript.Echo "Write to System Log: " & objOption.WriteToSystemLog


Enumerate WMI Settings

Description
Returns a list of WMI settings as configured on a computer.

Script Code

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


Identify a Global Catalog Server

Description
Indicates whether or not a specified domain controller is a global catalog server.

Script Code

strComputer = "atl-dc-01"

Const NTDSDSA_OPT_IS_GC = 1

Set objRootDSE = GetObject("LDAP://" & strComputer & "/rootDSE")
strDsServiceDN = objRootDSE.Get("dsServiceName")
Set objDsRoot  = GetObject("LDAP://" & strComputer & "/" & strDsServiceDN)
intOptions = objDsRoot.Get("options")

If intOptions And NTDSDSA_OPT_IS_GC Then
    WScript.Echo strComputer & " is a global catalog server."
Else
    Wscript.Echo strComputer & " is not a global catalog server."
End If


Identify Computer Chassis Type

Description
Retrieves an integer value indicating the chassis type for a computer (mini-tower, laptop, etc.). Script does not include a description of each value that can be returned.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colChassis = objWMIService.ExecQuery _
    ("Select * from Win32_SystemEnclosure")
For Each objChassis in colChassis
    For i = Lbound(objChassis.ChassisTypes) to Ubound(objChassis.ChassisTypes)
        Wscript.Echo objChassis.ChassisTypes(i)
    Next


Identify Computer Roles

Description
Returns the basic role (domain controller, member server, workstation, etc.) for a computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colComputers = objWMIService.ExecQuery _
    ("Select DomainRole from Win32_ComputerSystem")
For Each objComputer in colComputers
    Select Case objComputer.DomainRole
        Case 0
            strComputerRole = "Standalone Workstation"
        Case 1
            strComputerRole = "Member Workstation"
        Case 2
            strComputerRole = "Standalone Server"
        Case 3
            strComputerRole = "Member Server"
        Case 4
            strComputerRole = "Backup Domain Controller"
        Case 5
            strComputerRole = "Primary Domain Controller"
    End Select
    Wscript.Echo strComputerRole


Identify Computer Roles Using Services

Description
Indicates whether SQL Server is running on a computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service Where Name = 'MSSQLServer'")
If colServices.Count > 0 Then
    For Each objService in colServices
        Wscript.Echo "SQL Server is " & objService.State & "."
    Next
Else
    Wscript.Echo "SQL Server is not installed on this computer."
End If


Identify FSMO Roles

Description
Identify which Active Directory domain controllers are providing the five FSMO roles: Schema Master, Domain Naming Master, PDC Emulator, RID Master, and Infrastructure Master.

Script Code

Set objRootDSE = GetObject("LDAP://rootDSE")

' Schema Master
Set objSchema = GetObject("LDAP://" & objRootDSE.Get("schemaNamingContext"))
strSchemaMaster = objSchema.Get("fSMORoleOwner")
Set objNtds = GetObject("LDAP://" & strSchemaMaster)
Set objComputer = GetObject(objNtds.Parent)
WScript.Echo "Forest-wide Schema Master FSMO: " & objComputer.Name

Set objNtds = Nothing
Set objComputer = Nothing

' Domain Naming Master
Set objPartitions = GetObject("LDAP://CN=Partitions," & _
                              objRootDSE.Get("configurationNamingContext"))
strDomainNamingMaster = objPartitions.Get("fSMORoleOwner")
Set objNtds = GetObject("LDAP://" & strDomainNamingMaster)
Set objComputer = GetObject(objNtds.Parent)
WScript.Echo "Forest-wide Domain Naming Master FSMO: " & objComputer.Name

Set objNtds = Nothing
Set objComputer = Nothing

' PDC Emulator
Set objDomain = GetObject("LDAP://" & objRootDSE.Get("defaultNamingContext"))
strPdcEmulator = objDomain.Get("fSMORoleOwner")
Set objNtds = GetObject("LDAP://" & strPdcEmulator)
Set objComputer = GetObject(objNtds.Parent)
WScript.Echo "Domain's PDC Emulator FSMO: " & objComputer.Name

Set objNtds = Nothing
Set objComputer = Nothing

' RID Master
Set objRidManager = GetObject("LDAP://CN=RID Manager$,CN=System," & _
                              objRootDSE.Get("defaultNamingContext"))
strRidMaster = objRidManager.Get("fSMORoleOwner")
Set objNtds = GetObject("LDAP://" & strRidMaster)
Set objComputer = GetObject(objNtds.Parent)
WScript.Echo "Domain's RID Master FSMO: " & objComputer.Name

Set objNtds = Nothing
Set objComputer = Nothing

' Infrastructure Master
Set objInfrastructure = GetObject("LDAP://CN=Infrastructure," & _
                                  objRootDSE.Get("defaultNamingContext"))
strInfrastructureMaster = objInfrastructure.Get("fSMORoleOwner")
Set objNtds = GetObject("LDAP://" & strInfrastructureMaster)
Set objComputer = GetObject(objNtds.Parent)
WScript.Echo "Domain's Infrastructure Master FSMO: " & objComputer.Name


Identify the Latest Installed Service Pack

Description
Returns the last service pack to be installed on a computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colOperatingSystems = objWMIService.ExecQuery _
    ("Select * from Win32_OperatingSystem")
For Each objOperatingSystem in colOperatingSystems
    Wscript.Echo objOperatingSystem.ServicePackMajorVersion  _
        & "." & objOperatingSystem.ServicePackMinorVersion


Identify the Operating System

Description
Returns the name and version number of the operating system installed on a computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colOperatingSystems = objWMIService.ExecQuery _
    ("Select * from Win32_OperatingSystem")
For Each objOperatingSystem in colOperatingSystems
    Wscript.Echo objOperatingSystem.Caption & " " & objOperatingSystem.Version


Identify Windows Product Activation Status

Description
Returns product activation information for a computer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colWPA = objWMIService.ExecQuery _
    ("Select * from Win32_WindowsProductActivation")
For Each objWPA in colWPA
    Wscript.Echo "Activation Required: " & objWPA.ActivationRequired
    Wscript.Echo "Description: " & objWPA.Description
    Wscript.Echo "Product ID: " & objWPA.ProductID
    Wscript.Echo "Remaining Evaluation Period: " & _
        objWPA.RemainingEvaluationPeriod
    Wscript.Echo "Remaining Grace Period: " & objWPA.RemainingGracePeriod
    Wscript.Echo "Server Name: " & objWPA.ServerName


Install Software on a Remote Computer

Description
Installs a hypothetical software program (using a Windows Installer package) on a remote computer. Requires delegation for the computer and user accounts involved in the procedure.

Script Code

Const wbemImpersonationLevelDelegate = 4
Set objWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objConnection = objwbemLocator.ConnectServer _
    ("WebServer", "root\cimv2", "fabrikam\administrator", _
     "password", , "kerberos:WebServer")
objConnection.Security_.ImpersonationLevel = wbemImpersonationLevelDelegate
Set objSoftware = objConnection.Get("Win32_Product")
errReturn = objSoftware.Install("\\atl-dc-02\scripts\1561_lab.msi",,True)
Wscript.Echo errReturn


Install Software on the Local Computer

Description
Installs a hypothetical software program (using a Windows Installer package) on a local computer.

Script Code

Const ALL_USERS = True
Set objService = GetObject("winmgmts:")
Set objSoftware = objService.Get("Win32_Product")
errReturn = objSoftware.Install("c:\scripts\database.msi", , ALL_USERS)


Inventory Computer Hardware

Description
Returns information about the pointing devices installed on a computer. Used as an example of how to retrieve hardware information using WMI.

Script Code

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


Join Computer to a Domain

Description
Joins a computer to a domain and creates the computer's account in Active Directory.

Script Code

Const JOIN_DOMAIN             = 1
Const ACCT_CREATE             = 2
Const ACCT_DELETE             = 4
Const WIN9X_UPGRADE           = 16
Const DOMAIN_JOIN_IF_JOINED   = 32
Const JOIN_UNSECURE           = 64
Const MACHINE_PASSWORD_PASSED = 128
Const DEFERRED_SPN_SET        = 256
Const INSTALL_INVOCATION      = 262144

strDomain   = "FABRIKAM"
strPassword = "ls4k5ywA"
strUser     = "shenalan"

Set objNetwork = CreateObject("WScript.Network")
strComputer = objNetwork.ComputerName

Set objComputer = GetObject("winmgmts:{impersonationLevel=Impersonate}!\\" & _
                   strComputer & "\root\cimv2:Win32_ComputerSystem.Name='" & _
                   strComputer & "'")

ReturnValue = objComputer.JoinDomainOrWorkGroup(strDomain, _
                                                strPassword, _
                                                strDomain & "\" & strUser, _
                                                NULL, _
                                                JOIN_DOMAIN + ACCT_CREATE)


Modify Recovery Configuration Options

Description
Configures a computer to do a complete memory dump to the file C:\Scripts\memory.dmp should a stop event (blue screen) occur.

Script Code

Const COMPLETE_MEMORY_DUMP = 1
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colRecoveryOptions = objWMIService.ExecQuery _
    ("Select * from Win32_OSREcoveryConfiguration")
For Each objOption in colRecoveryOptions
    objOption.DebugInfoType = COMPLETE_MEMORY_DUMP
    objOption.DebugFilePath = "c:\scripts\memory.dmp"
    objOption.OverWriteExistingDebugFile = False
    objOption.Put_


Monitor Changes in Computer Power Status

Description
Issues an alert if a computer changes power state (for example, enters or leaves suspend mode).

Script Code

Set colMonitoredEvents = GetObject("winmgmts:")._
    ExecNotificationQuery("Select * from Win32_PowerManagementEvent")
Do
    Set strLatestEvent = colMonitoredEvents.NextEvent
    Wscript.Echo strLatestEvent.EventType
Loop


Move a Computer Account

Description
Moves a computer account from the Computers container in Active Directory to an OU.

Script Code

Set objNewOU = GetObject("LDAP://OU=Finance,DC=fabrikam,DC=com")
Set objMoveComputer = objNewOU.MoveHere _
    ("LDAP://CN=atl-pro-03,CN=Computers,DC=fabrikam,DC=com", "CN=atl-pro-03")


Query the Event Log for Stop Events

Description
Queries the System event log for any events written in regards to a stop event (blue screen).

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colLoggedEvents = objWMIService.ExecQuery _
    ("Select * from Win32_NTLogEvent Where Logfile = 'System'" _
        & " and SourceName = 'SaveDump'")
For Each objEvent in colLoggedEvents
    Wscript.Echo "Event date: " & objEvent.TimeGenerated
    Wscript.Echo "Description: " & objEvent.Message


Remove Software

Description
Uninstalls a hypothetical software program that was installed using Windows Installer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colSoftware = objWMIService.ExecQuery _
    ("Select * from Win32_Product Where Name = 'Personnel database'")
For Each objSoftware in colSoftware
    objSoftware.Uninstall()


Rename a Computer Account

Description
Renames an Active Directory computer account.

Script Code

Set objNewOU = GetObject("LDAP://OU=Finance,DC=fabrikam,DC=com")
Set objMoveComputer = objNewOU.MoveHere _
    ("LDAP://CN=atl-pro-037,OU=Finance,DC=fabrikam,DC=com", "CN=atl-pro-003")


Rename a Computer and Computer Account

Description
Renames a computer and its corresponding Active Directory computer account. Requires Windows XP or Windows .NET Server, and must be run on the local computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colComputers = objWMIService.ExecQuery _
    ("Select * from Win32_ComputerSystem")
For Each objComputer in colComputers
    err = ObjComputer.Rename("WebServer")
    Wscript.Echo err


Reset a Computer Account Password

Description
Resets a computer account password in Active Directory.

Script Code

Set objComputer = GetObject("LDAP://CN=atl-dc-01,CN=Computers,DC=Reskit,DC=COM")
objComputer.SetPassword "atl-dc-01$"


Restart a Computer

Description
Restarts a computer.

Script Code

strComputer = "atl-dc-01"
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate,(Shutdown)}!\\" & strComputer & "\root\cimv2")
Set colOperatingSystems = objWMIService.ExecQuery _
    ("Select * from Win32_OperatingSystem")
For Each objOperatingSystem in colOperatingSystems
    ObjOperatingSystem.Reboot()


Retrieve BIOS Information

Description
Retrieves BIOS information for a computer, including BIOS version number and release date.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colBIOS = objWMIService.ExecQuery _
    ("Select * from Win32_BIOS")
For each objBIOS in colBIOS
    Wscript.Echo "Build Number: " & objBIOS.BuildNumber
    Wscript.Echo "Current Language: " & objBIOS.CurrentLanguage
    Wscript.Echo "Installable Languages: " & objBIOS.InstallableLanguages
    Wscript.Echo "Manufacturer: " & objBIOS.Manufacturer
    Wscript.Echo "Name: " & objBIOS.Name
    Wscript.Echo "Primary BIOS: " & objBIOS.PrimaryBIOS
    Wscript.Echo "Release Date: " & objBIOS.ReleaseDate
    Wscript.Echo "Serial Number: " & objBIOS.SerialNumber
    Wscript.Echo "SMBIOS Version: " & objBIOS.SMBIOSBIOSVersion
    Wscript.Echo "SMBIOS Major Version: " & objBIOS.SMBIOSMajorVersion
    Wscript.Echo "SMBIOS Minor Version: " & objBIOS.SMBIOSMinorVersion
    Wscript.Echo "SMBIOS Present: " & objBIOS.SMBIOSPresent
    Wscript.Echo "Status: " & objBIOS.Status
    Wscript.Echo "Version: " & objBIOS.Version
    For i = 0 to Ubound(objBIOS.BiosCharacteristics)
        Wscript.Echo "BIOS Characteristics: " & _
            objBIOS.BiosCharacteristics(i)
    Next


Retrieve Operating System Properties

Description
Retrieves information about the operating system installed on a computer, including language, encryption level, and build number.

Script Code

Set dtmConvertedDate = CreateObject("WbemScripting.SWbemDateTime")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colOperatingSystems = objWMIService.ExecQuery _
    ("Select * from Win32_OperatingSystem")
For Each objOperatingSystem in colOperatingSystems
    Wscript.Echo "Boot Device: " & objOperatingSystem.BootDevice
    Wscript.Echo "Build Number: " & objOperatingSystem.BuildNumber
    Wscript.Echo "Build Type: " & objOperatingSystem.BuildType
    Wscript.Echo "Caption: " & objOperatingSystem.Caption
    Wscript.Echo "Code Set: " & objOperatingSystem.CodeSet
    Wscript.Echo "Country Code: " & objOperatingSystem.CountryCode
    Wscript.Echo "Debug: " & objOperatingSystem.Debug
    Wscript.Echo "Encryption Level: " & objOperatingSystem.EncryptionLevel
    dtmConvertedDate.Value = objOperatingSystem.InstallDate
    dtmInstallDate = dtmConvertedDate.GetVarDate
    Wscript.Echo "Install Date: " & dtmInstallDate
    Wscript.Echo "Licensed Users: " & _
        objOperatingSystem.NumberOfLicensedUsers
    Wscript.Echo "Organization: " & objOperatingSystem.Organization
    Wscript.Echo "OS Language: " & objOperatingSystem.OSLanguage
    Wscript.Echo "OS Product Suite: " & objOperatingSystem.OSProductSuite
    Wscript.Echo "OS Type: " & objOperatingSystem.OSType
    Wscript.Echo "Primary: " & objOperatingSystem.Primary
    Wscript.Echo "Registered User: " & objOperatingSystem.RegisteredUser
    Wscript.Echo "Serial Number: " & objOperatingSystem.SerialNumber
    Wscript.Echo "Version: " & objOperatingSystem.Version


Retrieve SMBIOS Information

Description
Retrieves part number, serial number, and asset tag number from SMBIOS-compliant computers.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colSMBIOS = objWMIService.ExecQuery _
    ("Select * from Win32_SystemEnclosure")
For Each objSMBIOS in colSMBIOS
    Wscript.Echo "Part Number: " & objSMBIOS.PartNumber
    Wscript.Echo "Serial Number: " & objSMBIOS.SerialNumber
    Wscript.Echo "Asset Tag: " & objSMBIOS.SMBIOSAssetTag


Retrieve System Information

Description
Uses WMI to retrieve the same data found in the System Information applet.

Script Code

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 "OS Name: " & 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


Search for Computer Accounts

Description
Returns the name and location for all the computer accounts in Active Directory that are running Windows .NET Server.

Script Code

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 Name, Location, operatingSystemVersion from 'LDAP://DC=fabrikam,DC=com'" _
       & " where objectClass='computer' and operatingSystemVersion = '5.1 (3600)'"
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Timeout") = 30
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCommand.Properties("Cache Results") = False
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
Do Until objRecordSet.EOF
    Wscript.Echo "Computer Name: " & objRecordSet.Fields("Name").Value
    Wscript.Echo "Location: " & objRecordSet.Fields("Location").Value
    objRecordSet.MoveNext
Loop


Shut Down the Local Computer

Description
Shuts down the local computer.

Script Code

Set colOperatingSystems = GetObject("winmgmts:{(Shutdown)}").ExecQuery("Select * from Win32_OperatingSystem")
For Each objOperatingSystem in colOperatingSystems
    ObjOperatingSystem.Win32Shutdown(1)


Upgrade Software

Description
Upgrades a hypothetical software program that was installed using Windows Installer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colSoftware = objWMIService.ExecQuery _
    ("Select * from Win32__Product Where Name = 'Personnel Database'")
For Each objSoftware in colSoftware
    errReturn = objSoftware.Upgrade("c:\scripts\database2.msi")


Add a Disk Quota Entry

Description
Creates a custom disk quota entry for a user named jsmith. This script must be run on the local computer.

Script Code

Set colDiskQuotas = CreateObject("Microsoft.DiskQuota.1")
colDiskQuotas.Initialize "C:\", True
set objUser = colDiskQuotas.AddUser("jsmith")
set objUser = colDiskQuotas.FindUser("jsmith")
objUser.QuotaLimit = 50000000


Bind to a Specific Disk Drive

Description
Demonstration script that uses the FileSystemObject to return available disk space on a specific disk drive. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objDrive = objFSO.GetDrive("C:")
Wscript.Echo "Available space: " & objDrive.AvailableSpace


Change Volume Names

Description
Changes the volume label for drive C to "Finance Volume."

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDrives = objWMIService.ExecQuery _
    ("Select * from Win32_LogicalDisk where DeviceID = 'C:'")
For Each objDrive in colDrives
    objDrive.VolumeName = "Finance Volume"
    objDrive.Put_


Configure Disk Quota Settings

Description
Changes the warning threshold and default quota limits for drive C. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colQuotaSettings = objWMIService.ExecQuery _
    ("Select * from Win32_QuotaSetting")
For each objQuotaSetting in colQuotaSettings
    objQuotaSetting.DefaultLimit = 10000000
    objQuotaSetting.DefaultWarningLimit = 9000000
    objQuotaSetting.Put_


Configure Page File Properties

Description
Sets the initial size of a page file to 300 megabytes, and the maximum size to 600 megabytes.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPageFiles = objWMIService.ExecQuery _
    ("Select * from Win32_PageFileSetting")
For Each objPageFile in colPageFiles
    objPageFile.InitialSize = 300
    objPageFile.MaximumSize = 600
    objPageFile.Put_


Create a Dfs Node

Description
Creates a new Dfs node for a shared folder named Scripts. Requires Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objDfsNode = objWMIService.Get("Win32_DfsNode")
errReturn = objDfsNode.Create _
    ("\\atl-dc-02\Scripts","\\atl-dc-02","Scripts", _
        "New Dfs node for shared scripts.")
Wscript.Echo errReturn


Delete a Disk Quota Entry

Description
Deletes the disk quota entry for a user named jsmith. This script must be run on the local computer.

Script Code

Set colDiskQuotas = CreateObject("Microsoft.DiskQuota.1")
colDiskQuotas.Initialize "C:\", True
set objUser = colDiskQuotas.FindUser("jsmith")
colDiskQuotas.DeleteUser(objUser)


Enable Disk Quotas

Description
Turns on disk quotas for drive C. Requires Windows XP or Windows .NET Server.

Script Code

Const ENFORCE_QUOTAS = 1
StrComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDisks = objWMIService.ExecQuery _
    ("Select * from Win32_QuotaSetting Where VolumePath = 'C:\\'")
For Each objDisk in colDisks
    objDisk.State = ENFORCE_QUOTAS
    objDisk.Put_


Ensure that All Drives are Ready

Description
Demonstration script that uses the FileSystemObject to ensure that all drives are ready (i.e., media is inserted) before echoing the drive letter and available disk space. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set colDrives = objFSO.Drives
For Each objDrive in colDrives
    If objDrive.IsReady = True Then
        Wscript.Echo "Drive letter: " & objDrive.DriveLetter
        Wscript.Echo "Free space: " & objDrive.FreeSpace
    Else
        Wscript.Echo "Drive letter: " & objDrive.DriveLetter
    End If


Enumerate Available Disk Space

Description
Returns the amount of free space for each hard disk installed on a computer.

Script Code

Const HARD_DISK = 3
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDisks = objWMIService.ExecQuery _
    ("Select * from Win32_LogicalDisk Where DriveType = " & HARD_DISK & "")
For Each objDisk in colDisks
    Wscript.Echo "DeviceID: "& vbTab &  objDisk.DeviceID
    Wscript.Echo "Free Disk Space: "& vbTab & objDisk.FreeSpace


Enumerate Dfs Nodes

Description
Enumerates all the Dfs nodes on a computer. Requires Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDfsNodes = objWMIService.ExecQuery _
    ("Select * from Win32_DFSNode")
For each objDfsNode in colDfsNodes
    Wscript.Echo "Caption: " & vbTab &  objDfsNode.Caption
    Wscript.Echo "Description: " & vbTab &  objDfsNode.Description
    Wscript.Echo "Install Date: " & vbTab &  objDfsNode.InstallDate
    Wscript.Echo "Name: " & vbTab &  objDfsNode.Name
    Wscript.Echo "Root: " & vbTab &  objDfsNode.Root
    Wscript.Echo "State: " & vbTab &  objDfsNode.State
    Wscript.Echo "Status: " & vbTab &  objDfsNode.Status
    Wscript.Echo "Timeout: " & vbTab &  objDfsNode.Timeout


Enumerate Dfs Targets

Description
Enumerates all the Dfs targets on a computer. Requires Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDfsTargets = objWMIService.ExecQuery _
    ("Select * from Win32_DFSTarget")
For each objDfsTarget in colDfsTargets
    Wscript.Echo "Caption: " & vbTab &  objDfsTarget.Caption
    Wscript.Echo "Description: " & vbTab &  objDfsTarget.Description
    Wscript.Echo "Install Date: " & vbTab &  objDfsTarget.InstallDate
    Wscript.Echo "Link Name: " & vbTab &  objDfsTarget.LinkName
    Wscript.Echo "Name: " & vbTab &  objDfsTarget.Name
    Wscript.Echo "Server Name: " & vbTab &  objDfsTarget.ServerName
    Wscript.Echo "Share Name: " & vbTab &  objDfsTarget.ShareName
    Wscript.Echo "State: " & vbTab &  objDfsTarget.State
    Wscript.Echo "Status: " & vbTab &  objDfsTarget.Status


Enumerate Disk Drive Properties Using FSO

Description
Demonstration script that uses the FileSystemObject to return the properties of all the disk drives installed on a computer. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set colDrives = objFSO.Drives
For Each objDrive in colDrives
    Wscript.Echo "Available space: " & objDrive.AvailableSpace
    Wscript.Echo "Drive letter: " & objDrive.DriveLetter
    Wscript.Echo "Drive type: " & objDrive.DriveType
    Wscript.Echo "File system: " & objDrive.FileSystem
    Wscript.Echo "Free space: " & objDrive.FreeSpace
    Wscript.Echo "Is ready: " & objDrive.IsReady
    Wscript.Echo "Path: " & objDrive.Path
    Wscript.Echo "Root folder: " & objDrive.RootFolder
    Wscript.Echo "Serial number: " & objDrive.SerialNumber
    Wscript.Echo "Share name: " & objDrive.ShareName
    Wscript.Echo "Total size: " & objDrive.TotalSize
    Wscript.Echo "Volume name: " & objDrive.VolumeName


Enumerate Disk Partition Properties

Description
Lists the properties for all the disk partitions on a computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDiskPartitions = objWMIService.ExecQuery _
    ("Select * from Win32_DiskPartition")
For each objPartition in colDiskPartitions
    Wscript.Echo "Block Size: " & vbTab &  objPartition.BlockSize
    Wscript.Echo "Bootable: " & vbTab &  objPartition.Bootable
    Wscript.Echo "Boot Partition: " & vbTab &  objPartition.BootPartition
    Wscript.Echo "Description: " & vbTab &  objPartition.Description
    Wscript.Echo "Device ID: " & vbTab &  objPartition.DeviceID
    Wscript.Echo "Disk Index: " & vbTab &  objPartition.DiskIndex
    Wscript.Echo "Index: " & vbTab &  objPartition.Index
    Wscript.Echo "Name: " & vbTab &  objPartition.Name
    Wscript.Echo "Number Of Blocks: " & vbTab &  _
        objPartition.NumberOfBlocks
    Wscript.Echo "Primary Partition: " & vbTab &  _
        objPartition.PrimaryPartition
    Wscript.Echo "Size: " & vbTab &  objPartition.Size
    Wscript.Echo "Starting Offset: " & vbTab &  _
        objPartition.StartingOffset
    Wscript.Echo "Type: " & vbTab &  objPartition.Type


Enumerate Disk Quotas

Description
Enumerates disk quota information (including user name, warning and quota limits, and disk space used) for each disk quota entry on a computer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDiskQuotas = objWMIService.ExecQuery _
   ("Select * from Win32_DiskQuota")
For each objQuota in colDiskQuotas
    Wscript.Echo "Disk Space Used: " & vbTab &  objQuota.DiskSpaceUsed
    Wscript.Echo "Limit: " & vbTab &  objQuota.Limit
    Wscript.Echo "Quota Volume: " & vbTab &  objQuota.QuotaVolume
    Wscript.Echo "Status: " & vbTab &  objQuota.Status
    Wscript.Echo "User: " & vbTab &  objQuota.User
    Wscript.Echo "Warning Limit: " & vbTab &  objQuota.WarningLimit


Enumerate Disk Quota Settings

Description
Enumerates the disk quota settings for each drive on a computer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colQuotaSettings = objWMIService.ExecQuery _
    ("Select * from Win32_QuotaSetting")
For each objQuotaSetting in colQuotaSettings
    Wscript.Echo "DefaultLimit: " & vbTab &  objQuotaSetting.DefaultLimit
    Wscript.Echo "DefaultWarningLimit: " & vbTab &  _
        objQuotaSetting.DefaultWarningLimit
    Wscript.Echo "ExceededNotification: " & vbTab &  _
        objQuotaSetting.ExceededNotification
    Wscript.Echo "State: " & vbTab &  objQuotaSetting.State
    Wscript.Echo "VolumePath: " & vbTab &  objQuotaSetting.VolumePath
    Wscript.Echo "WarningExceededNotification: " & vbTab &  _
        objQuotaSetting.WarningExceededNotification


Enumerate Disk Space by User Using Disk Quotas

Description
Uses disk quotas to report the amount of disk space being used by each individual user on a computer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colQuotas = objWMIService.ExecQuery _
    ("Select * from Win32_DiskQuota")
For each objQuota in colQuotas
    Wscript.Echo "Volume: "& vbTab &  objQuota.QuotaVolume
    Wscript.Echo "User: "& vbTab &  objQuota.User
    Wscript.Echo "Disk Space Used: "& vbTab &  objQuota.DiskSpaceUsed


Enumerate Logical Disk Drive Properties

Description
Lists the properties for all the logical disk drives on a computer. Includes mapped network drives.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDisks = objWMIService.ExecQuery _
    ("Select * from Win32_LogicalDisk")
For each objDisk in colDisks
    Wscript.Echo "Compressed: " & vbTab &  objDisk.Compressed
    Wscript.Echo "Description: " & vbTab &  objDisk.Description
    Wscript.Echo "DeviceID: " & vbTab &  objDisk.DeviceID
    Wscript.Echo "DriveType: " & vbTab &  objDisk.DriveType
    Wscript.Echo "FileSystem: " & vbTab &  objDisk.FileSystem
    Wscript.Echo "FreeSpace: " & vbTab &  objDisk.FreeSpace
    Wscript.Echo "MediaType: " & vbTab &  objDisk.MediaType
    Wscript.Echo "Name: " & vbTab &  objDisk.Name
    Wscript.Echo "QuotasDisabled: " & vbTab &  objDisk.QuotasDisabled
    Wscript.Echo "QuotasIncomplete: " & vbTab &  objDisk.QuotasIncomplete
    Wscript.Echo "QuotasRebuilding: " & vbTab &  objDisk.QuotasRebuilding
    Wscript.Echo "Size: " & vbTab &  objDisk.Size
    Wscript.Echo "SupportsDiskQuotas: " & vbTab & _
        objDisk.SupportsDiskQuotas
    Wscript.Echo "SupportsFileBasedCompression: " & vbTab & _
        objDisk.SupportsFileBasedCompression
    Wscript.Echo "SystemName: " & vbTab &  objDisk.SystemName
    Wscript.Echo "VolumeDirty: " & vbTab &  objDisk.VolumeDirty
    Wscript.Echo "VolumeName: " & vbTab &  objDisk.VolumeName
    Wscript.Echo "VolumeSerialNumber: " & vbTab &  _
        objDisk.VolumeSerialNumber


Enumerate NTFS Properties

Description
Retrieves NTFS file system settings from the registry.

Script Code

On Error Resume Next
Set objShell = WScript.CreateObject("WScript.Shell")
strRegKey =  objShell.RegRead _
    ("HKLM\System\CurrentControlSet\Control\FileSystem\" _
        & "NtfsDisable8dot3NameCreation")
If IsNull(strRegKey) Then
    Wscript.Echo "No value set for disabling 8.3 file name creation."
ElseIf strRegKey = 1 Then
    WScript.Echo "No 8.3 file names will be created for new files."
ElseIf strRegKey = 0 Then
    Wscript.Echo "8.3 file names will be created for new files."
End If
strRegKey = Null
strRegKey =  objShell.RegRead _
    ("HKLM\System\CurrentControlSet\Control\FileSystem\" _
        & "NtfsAllowExtendedCharacterIn8Dot3Name")
If IsNull(strRegKey) Then
    Wscript.Echo "No value set for allowing extended characters in " _
       & " 8.3 file names."
ElseIf strRegKey = 1 Then
    WScript.Echo "Extended characters are permitted in 8.3 file names."
ElseIf strRegKey = 0 Then
    Wscript.Echo "Extended characters not permitted in 8.3 file names."
End If
strRegKey = Null
strRegKey =  objShell.RegRead _
    ("HKLM\System\CurrentControlSet\Control\FileSystem\" _
        & "NtfsMftZoneReservation")
If IsNull(strRegKey) Then
    Wscript.Echo "No value set for reserving the MFT zone."
ElseIf strRegKey = 1 Then
    WScript.Echo "One-eighth of the disk has been reserved for the MFT zone."
ElseIf strRegKey = 2 Then
    Wscript.Echo "One-fourth of the disk reserved for the MFT zone."
ElseIf strRegKey = 3 Then
    Wscript.Echo "Three-eighths of the disk reserved for the MFT zone."
ElseIf strRegKey = 4 Then
    Wscript.Echo "One half of the disk reserved for the MFT zone."
End If
strRegKey = Null
strRegKey =  objShell.RegRead _
    ("HKLM\System\CurrentControlSet\Control\FileSystem\" _
        & "NtfsDisableLastAccessUpdate")
If IsNull(strRegKey) Then
    Wscript.Echo "No value set for disabling the last access update " _
        & "for files and folder."
ElseIf strRegKey = 1 Then
    WScript.Echo "The last access timestamp will not be updated on files " _
        & "and folders."
ElseIf strRegKey = 0 Then
    Wscript.Echo "The last access timestamp updated on files and " _
         & "folders."
End If
strRegKey = Null
strRegKey =  objShell.RegRead _
    ("HKLM\System\CurrentControlSet\Control\FileSystem\Win31FileSystem")
If IsNull(strRegKey) Then
    Wscript.Echo "No value set for using long file names and " _
        & "timestamps."
ElseIf strRegKey = 1 Then
    WScript.Echo "Long file names and extended timestamps are used."
ElseIf strRegKey = 0 Then
    Wscript.Echo "Long file names and extended timestamps are not used."
End If


Enumerate Page File Properties

Description
Enumerates the properties of all the page files on a computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPageFiles = objWMIService.ExecQuery _
    ("Select * from Win32_PageFile")
For each objPageFile in colPageFiles
    Wscript.Echo "CreationDate: " & vbTab &  objPageFile.CreationDate
    Wscript.Echo "Description: " & vbTab &  objPageFile.Description
    Wscript.Echo "Drive: " & vbTab &  objPageFile.Drive
    Wscript.Echo "FileName: " & vbTab &  objPageFile.FileName
    Wscript.Echo "FileSize: " & vbTab &  objPageFile.FileSize
    Wscript.Echo "InitialSize: " & vbTab &  objPageFile.InitialSize
    Wscript.Echo "InstallDate: " & vbTab &  objPageFile.InstallDate
    Wscript.Echo "MaximumSize: " & vbTab &  objPageFile.MaximumSize
    Wscript.Echo "Name: " & vbTab &  objPageFile.Name
    Wscript.Echo "Path: " & vbTab &  objPageFile.Path


Enumerate Physical Disk Properties

Description
Retrieves the properties for all the physical disk drives installed on a computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer _
        & "\root\cimv2")
Set colDiskDrives = objWMIService.ExecQuery _
    ("Select * from Win32_DiskDrive")
For each objDiskDrive in colDiskDrives
    Wscript.Echo "Bytes Per Sector: " & vbTab &  _
        objDiskDrive.BytesPerSector
    For i = Lbound(objDiskDrive.Capabilities) to _
        Ubound(objDiskDrive.Capabilities)
        Wscript.Echo "Capabilities: " & vbTab &  _
            objDiskDrive.Capabilities(i)
    Next
    Wscript.Echo "Caption: " & vbTab &  objDiskDrive.Caption
    Wscript.Echo "Device ID: " & vbTab &  objDiskDrive.DeviceID
    Wscript.Echo "Index: " & vbTab &  objDiskDrive.Index
    Wscript.Echo "Interface Type: " & vbTab & objDiskDrive.InterfaceType
    Wscript.Echo "Manufacturer: " & vbTab & objDiskDrive.Manufacturer
    Wscript.Echo "Media Loaded: " & vbTab  & objDiskDrive.MediaLoaded
    Wscript.Echo "Media Type: " & vbTab &  objDiskDrive.MediaType
    Wscript.Echo "Model: " & vbTab &  objDiskDrive.Model
    Wscript.Echo "Name: " & vbTab &  objDiskDrive.Name
    Wscript.Echo "Partitions: " & vbTab & objDiskDrive.Partitions
    Wscript.Echo "PNP DeviceID: " & vbTab &  objDiskDrive.PNPDeviceID
    Wscript.Echo "SCSI Bus: " & vbTab &  objDiskDrive.SCSIBus
    Wscript.Echo "SCSI Logical Unit: " & vbTab &  _
        objDiskDrive.SCSILogicalUnit
    Wscript.Echo "SCSI Port: " & vbTab &  objDiskDrive.SCSIPort
    Wscript.Echo "SCSI TargetId: " & vbTab &  objDiskDrive.SCSITargetId
    Wscript.Echo "Sectors Per Track: " & vbTab &  _
        objDiskDrive.SectorsPerTrack
    Wscript.Echo "Signature: " & vbTab &  objDiskDrive.Signature
    Wscript.Echo "Size: " & vbTab &  objDiskDrive.Size
    Wscript.Echo "Status: " & vbTab &  objDiskDrive.Status
    Wscript.Echo "Total Cylinders: " & vbTab &  _
        objDiskDrive.TotalCylinders
    Wscript.Echo "Total Heads: " & vbTab &  objDiskDrive.TotalHeads
    Wscript.Echo "Total Sectors: " & vbTab &  objDiskDrive.TotalSectors
    Wscript.Echo "Total Tracks: " & vbTab &  objDiskDrive.TotalTracks
    Wscript.Echo "Tracks Per Cylinder: " & vbTab &  _
        objDiskDrive.TracksPerCylinder


Identify Drive Types

Description
Identifies the drive type (floppy drive, hard drive, CD-ROM, etc.) for each physical drive installed on a computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDisks = objWMIService.ExecQuery _
    ("Select * from Win32_LogicalDisk")
For Each objDisk in colDisks
    Wscript.Echo "DeviceID: "& vbTab &  objDisk.DeviceID
    Select Case objDisk.DriveType
        Case 1
            Wscript.Echo "No root directory. Drive type could not be " _
                & "determined."
        Case 2
            Wscript.Echo "DriveType: "& vbTab &  "Removable drive."
        Case 3
            Wscript.Echo "DriveType: "& vbTab &  "Local hard disk."
        Case 4
            Wscript.Echo "DriveType: "& vbTab &  "Network disk."
        Case 5
            Wscript.Echo "DriveType: "& vbTab &  "Compact disk."
        Case 6
            Wscript.Echo "DriveType: "& vbTab &  "RAM disk."
        Case Else
            Wscript.Echo "Drive type could not be determined."
    End Select


Identify the File System Type

Description
Returns the type of file system (FAT, NTFS, FAT32, etc.) used on each drive in a computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDisks = objWMIService.ExecQuery _
    ("Select * from Win32_LogicalDisk")
For Each objDisk in colDisks
    Wscript.Echo "DeviceID: "& vbTab &  objDisk.DeviceID
    Wscript.Echo "File System: "& vbTab & objDisk.FileSystem


Modify a Disk Quota Entry

Description
Modifies the disk quota warning threshold and disk space limit for a user named jsmith. This script must be run on the local computer.

Script Code

Set colDiskQuotas = CreateObject("Microsoft.DiskQuota.1")
colDiskQuotas.Initialize "C:\", True
set objUser = colDiskQuotas.FindUser("jsmith")
objUser.QuotaThreshold = 90000000
objUser.QuotaLimit = 100000000


Modify File System Properties

Description
Disables the updating of the last access time for files and folders.

Script Code

Set objShell = WScript.CreateObject("WScript.Shell")
strRegKey =  objShell.RegWrite _
    ("HKLM\System\CurrentControlSet\Control\FileSystem\" _
        & "NtfsDisableLastAccessUpdate" , 1, "REG_DWORD")


Modify the AutoChk Timeout Value

Description
Sets the auto-delay time for Autochk.exe to 30 seconds. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colAutoChkSettings = objWMIService.ExecQuery _
    ("Select * from Win32_AutochkSetting")
For Each objAutoChkSetting in colAutoChkSettings
    objAutoChkSetting.UserInputDelay = 30
    objAutoChkSetting.Put_


Monitor Available Disk Space

Description
Issues an alert if free disk space for any hard drive on a computer falls below 100 megabytes.

Script Code

Const LOCAL_HARD_DISK = 3
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colMonitoredDisks = objWMIService.ExecNotificationQuery _
    ("Select * from __instancemodificationevent within 30 where " _
        & "TargetInstance isa 'Win32_LogicalDisk'")
i = 0
Do While i = 0
    Set objDiskChange = colMonitoredDisks.NextEvent
    If objDiskChange.TargetInstance.DriveType = LOCAL_HARD_DISK Then
        If objDiskChange.TargetInstance.Size < 100000000 Then
            Wscript.Echo "Hard disk space is below 100000000 bytes."
        End If
    End If
Loop


Monitor Logical Disk Drive Performance

Description
Uses cooked performance counters to monitor performance of the logical disk drives installed on a computer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
set objRefresher = CreateObject("WbemScripting.SWbemRefresher")
Set colDisks = objRefresher.AddEnum _
    (objWMIService, "win32_perfformatteddata_perfdisk_logicaldisk"). _
        objectSet
objRefresher.Refresh
For i = 1 to 100
    For Each objDisk in colDisks
        Wscript.Echo "Average Disk Bytes Per Read: " & vbTab &  _
            objDisk.AvgDiskBytesPerRead
        Wscript.Echo "Average Disk Bytes Per Transfer: " & vbTab &  _
            objDisk.AvgDiskBytesPerTransfer
        Wscript.Echo "Average Disk Bytes Per Write: " & vbTab &  _
            objDisk.AvgDiskBytesPerWrite
        Wscript.Echo "Average Disk Queue Length: " & vbTab &  _
            objDisk.AvgDiskQueueLength
        Wscript.Echo "Average Disk Read Queue Length: " & vbTab &  _
            objDisk.AvgDiskReadQueueLength
        Wscript.Echo "Average Disk Seconds Per Read: " & vbTab &  _
            objDisk.AvgDiskSecPerRead
        Wscript.Echo "Average Disk Seconds Per Transfer: " & vbTab &  _
            objDisk.AvgDiskSecPerTransfer
        Wscript.Echo "Average Disk Seconds Per Write: " & vbTab &  _
            objDisk.AvgDiskSecPerWrite
        Wscript.Echo "Average Disk Write Queue Length: " & vbTab &  _
            objDisk.AvgDiskWriteQueueLength
        Wscript.Echo "Current Disk Queue Length: " & vbTab &  _
            objDisk.CurrentDiskQueueLength
        Wscript.Echo "Disk Bytes Per Second: " & vbTab &  _
            objDisk.DiskBytesPerSec
        Wscript.Echo "Disk Read Bytes Per Second: " & vbTab &  _
            objDisk.DiskReadBytesPerSec
        Wscript.Echo "Disk Reads Per Second: " & vbTab &  _
            objDisk.DiskReadsPerSec
        Wscript.Echo "Disk Transfers Per Second: " & vbTab &  _
            objDisk.DiskTransfersPerSec
        Wscript.Echo "Disk Write Bytes Per Second: " & vbTab &  _
            objDisk.DiskWriteBytesPerSec
        Wscript.Echo "Disk Writes Per Second: " & vbTab &  _
            objDisk.DiskWritesPerSec
        Wscript.Echo "Free Megabytes: " & vbTab &  objDisk.FreeMegabytes
        Wscript.Echo "Name: " & vbTab &  objDisk.Name
        Wscript.Echo "Percent Disk Read Time: " & vbTab &  _
            objDisk.PercentDiskReadTime
        Wscript.Echo "Percent Disk Time: " & vbTab &  _
            objDisk.PercentDiskTime
        Wscript.Echo "Percent Disk Write Time: " & vbTab &  _
            objDisk.PercentDiskWriteTime
        Wscript.Echo "Percent Free Space: " & vbTab &  _
            objDisk.PercentFreeSpace
        Wscript.Echo "Percent Idle Time: " & vbTab &  _
            objDisk.PercentIdleTime
        Wscript.Echo "Split IO Per Second: " & vbTab &  _
            objDisk.SplitIOPerSec
        Wscript.Sleep 2000
        objRefresher.Refresh
    Next


Monitor NTFS File Cache Performance

Description
Uses cooked performance counters to monitor the performance of the NTFS file cache. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
set objRefresher = CreateObject("WbemScripting.SWbemRefresher")
Set colCache = objRefresher.AddEnum _
    (objWMIService, "win32_PerfFormattedData_PerfOS_Cache").ObjectSet
objRefresher.Refresh
For i = 1 to 100
    For Each objCache in colCache
        Wscript.Echo "Async Copy Reads Per Second" & vbTab & _
            objCache.AsyncCopyReadsPerSec
        Wscript.Echo "Async Data Maps Per Second" & vbTab & _
            objCache.AsyncDataMapsPerSec
        Wscript.Echo "AsyncFastReadsPerSecond" & vbTab & _
            objCache.AsyncFastReadsPerSec
        Wscript.Echo "Async MDL Reads Per Second" & vbTab & _
            objCache.AsyncMDLReadsPerSec
        Wscript.Echo "Async Pin Reads Per Second" & vbTab & _
            objCache.AsyncPinReadsPerSec
        Wscript.Echo "Caption" & vbTab & objCache.Caption
        Wscript.Echo "Copy Read Hits Percent " & vbTab & _
            objCache.CopyReadHitsPercent
        Wscript.Echo "Copy Reads Per Second" & vbTab & _
            objCache.CopyReadsPerSec
        Wscript.Echo "Data Flushes Per Second" & vbTab & _
            objCache.DataFlushesPerSec
        Wscript.Echo "Data Flush Pages PerSecond" & vbTab & _
            objCache.DataFlushPagesPerSec
        Wscript.Echo "Data Map Hits Percent " & vbTab &  _
            objCache.DataMapHitsPercent
        Wscript.Echo "Data Map Pins Per Second" & vbTab & _
            objCache.DataMapPinsPerSec
        Wscript.Echo "Data Maps Per Second" & vbTab & _
            objCache.DataMapsPerSec
        Wscript.Echo "Description" & vbTab & objCache.Description
        Wscript.Echo "Fast Read Not Possibles Per Second" & vbTab & _
            objCache.FastReadNotPossiblesPerSec
        Wscript.Echo "Fast Read Resource Misses Per Second" & vbTab & _
            objCache.FastReadResourceMissesPerSec
        Wscript.Echo "Fast Reads Per Second" & vbTab & _
            objCache.FastReadsPerSec
        Wscript.Echo "Lazy Write Flushes Per Second" & vbTab & _
            objCache.LazyWriteFlushesPerSec
        Wscript.Echo "Lazy Write Pages Per Second" & vbTab & _
            objCache.LazyWritePagesPerSec
        Wscript.Echo "MDL Read Hits Percent " & vbTab & _
            objCache.MDLReadHitsPercent
        Wscript.Echo "MDL Reads Per Second" & vbTab & _
            objCache.MDLReadsPerSec
        Wscript.Echo "Name" & vbTab & objCache.Name
        Wscript.Echo "Pin Read Hits Percent" & vbTab & _
            objCache.PinReadHitsPercent
        Wscript.Echo "Pin Reads Per Second" & vbTab & _
            objCache.PinReadsPerSec
        Wscript.Echo "Read Aheads Per Second" & vbTab & _
            objCache.ReadAheadsPerSec
        Wscript.Echo "Sync Copy Reads Per Second" & vbTab & _
            objCache.SyncCopyReadsPerSec
        Wscript.Echo "Sync Data Maps Per Second" & vbTab & _
            objCache.SyncDataMapsPerSec
        Wscript.Echo "Sync Fast Reads Per Second" & vbTab & _
            objCache.SyncFastReadsPerSec
        Wscript.Echo "Sync MDL Reads Per Second" & vbTab & _
            objCache.SyncMDLReadsPerSec
        Wscript.Echo "Sync Pin Reads Per Second" & vbTab & _
            objCache.SyncPinReadsPerSec
        Wscript.Sleep 2000
        objRefresher.Refresh
    Next


Monitor Page File Use

Description
Retrieves page file usage statistics.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPageFiles = objWMIService.ExecQuery _
    ("Select * from Win32_PageFileUsage")
For each objPageFile in colPageFiles
    Wscript.Echo "AllocatedBaseSize: "& vbTab &  objPageFile.AllocatedBaseSize
    Wscript.Echo "CurrentUsage: "& vbTab &  objPageFile.CurrentUsage
    Wscript.Echo "Description: "& vbTab &  objPageFile.Description
    Wscript.Echo "InstallDate: "& vbTab &  objPageFile.InstallDate
    Wscript.Echo "Name: "& vbTab &  objPageFile.Name
    Wscript.Echo "PeakUsage: "& vbTab &  objPageFile.PeakUsage


Monitor Physical Disk Drive Performance

Description
Uses cooked performance counters to monitor performance of the physical disk drives installed on a computer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
set objRefresher = CreateObject("WbemScripting.SWbemRefresher")
Set colDisks = objRefresher.AddEnum _
    (objWMIService, "win32_perfformatteddata_perfdisk_physicaldisk"). _
        objectSet
objRefresher.Refresh
For i = 1 to 100
    For Each objDisk in colDisks
        Wscript.Echo "Average Disk Bytes Per Read: " & vbTab &  _
            objDisk.AvgDiskBytesPerRead
        Wscript.Echo "Average Disk Bytes Per Transfer: " & vbTab &  _
            objDisk.AvgDiskBytesPerTransfer
        Wscript.Echo "Average Disk Bytes Per Write: " & vbTab &  _
            objDisk.AvgDiskBytesPerWrite
        Wscript.Echo "Average Disk Queue Length: " & vbTab &  _
           objDisk.AvgDiskQueueLength
        Wscript.Echo "Average Disk Read Queue Length: " & vbTab &  _
            objDisk.AvgDiskReadQueueLength
        Wscript.Echo "Average Disk Seconds Per Read: " & vbTab &  _
            objDisk.AvgDiskSecPerRead
        Wscript.Echo "Average Disk Seconds Per Transfer: " & vbTab &  _
            objDisk.AvgDiskSecPerTransfer
        Wscript.Echo "Average Disk Seconds Per Write: " & vbTab &  _
            objDisk.AvgDiskSecPerWrite
        Wscript.Echo "Average Disk Write Queue Length: " & vbTab &  _
            objDisk.AvgDiskWriteQueueLength
        Wscript.Echo "Current Disk Queue Length: " & vbTab &  _
            objDisk.CurrentDiskQueueLength
        Wscript.Echo "Disk Bytes Per Second: " & vbTab &  _
            objDisk.DiskBytesPerSec
        Wscript.Echo "Disk Read Bytes Per Second: " & vbTab &  _
            objDisk.DiskReadBytesPerSec
        Wscript.Echo "Disk Reads Per Second: " & vbTab &  _
            objDisk.DiskReadsPerSec
        Wscript.Echo "Disk Transfers Per Second: " & vbTab &  _
            objDisk.DiskTransfersPerSec
        Wscript.Echo "Disk Write Bytes Per Second: " & vbTab &  _
            objDisk.DiskWriteBytesPerSec
        Wscript.Echo "Disk Writes Per Second: " & vbTab &  _
            objDisk.DiskWritesPerSec
        Wscript.Echo "Name: " & vbTab &  objDisk.Name
        Wscript.Echo "Percent Disk Read Time: " & vbTab &  _
            objDisk.PercentDiskReadTime
        Wscript.Echo "Percent Disk Time: " & vbTab &  _
            objDisk.PercentDiskTime
        Wscript.Echo "Percent Disk Write Time: " & vbTab &  _
            objDisk.PercentDiskWriteTime
        Wscript.Echo "Percent Idle Time: " & vbTab &  _
            objDisk.PercentIdleTime
        Wscript.Echo "Split IO Per Second: " & vbTab &  _
            objDisk.SplitIOPerSec
        Wscript.Sleep 2000
        objRefresher.Refresh
    Next


Monitor Volume Change Events

Description
Temporary event consumer that issues an alert when local volumes are added to or deleted from a computer. (This class monitors only changes to local drives; it cannot detect the addition/deletion of network volumes.) Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colMonitoredEvents = objWMIService. _
    ExecNotificationQuery("Select * from Win32_VolumeChangeEvent")
Do
    Set objLatestEvent = colMonitoredEvents.NextEvent
    Wscript.Echo objLatestEvent.DriveName
    Wscript.Echo objLatestEvent.EventType
    Wscript.Echo objLatestEvent.Time_Created
Loop


Prevent AutoChk From Running

Description
Ensures that Autochk.exe will not run against drive C the next time the computer reboots, even if the "dirty bit" has been set on drive C. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objDisk = objWMIService.Get("Win32_LogicalDisk")
errReturn = objDisk.ExcludeFromAutoChk(Array("C:"))
Wscript.Echo errReturn


Run ChkDsk

Description
Runs ChkDks.exe against drive D on a computer. Requires Windows XP or Windows .NET Server.

Script Code

Const FIX_ERRORS = True
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objDisk = objService.Get("Win32_LogicalDisk.DeviceID='D:'")
errReturn = objDisk.ChkDsk(FIX_ERRORS)
Wscript.Echo errReturn


Schedule AutoChk

Description
Schedules Autochk.exe to run against drive C the next time the computer reboots. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objDisk = objWMIService.Get("Win32_LogicalDisk")
errReturn = objDisk.ScheduleAutoChk(Array("C:"))
Wscript.Echo errReturn


Verify ChkDsk Volume Status

Description
Indicates whether or not any hard drives on a computer have the "dirty bit" set, and should have Chkdsk.exe run. Requires Windows XP or Windows .NET Server.

Script Code

Const LOCAL_HARD_DISK = 3
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDisks = objWMIService.ExecQuery _
    ("Select * from Win32_LogicalDisk Where DriveType = LOCAL_HARD_DISK ")
For Each objDisk in colDisks
    Wscript.Echo "DeviceID: "& vbTab &  objDisk.DeviceID
    Wscript.Echo "DriveType: "& vbTab & objDisk.VolumeDirty


Clear a Database Table

Description
Demonstration script that deletes all the records in a table named Hardware from an ADO database with the DSN "Inventory."

Script Code

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


Create an Instance of Internet Explorer

Description
Demonstration script that creates an instance of Internet Explorer, opened to a blank page.

Script Code

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


Delete a Record from a Recordset

Description
Demonstration script that deletes the record for a computer named WebServer from an ADO database with the DSN "Inventory."

Script Code

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


Display Tabular Output in a Command Window

Description
Retrieves service data from a computer, and then outputs that data in tabular format in a command window.

Script Code

Set colServices = GetObject("winmgmts:"). _
    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


Mask Command Line Passwords

Description
Demonstration script that uses ScriptPW.dll to mask passwords entered at the command line. Requires Windows XP or Windows .NET Server.

Script Code

Set objPassword = CreateObject("ScriptPW.Password")
WScript.StdOut.Write "Please enter your password:"
strPassword = objPassword.GetPassword()
Wscript.Echo
Wscript.Echo "Your password is: " & strPassword


Mask Passwords Using Internet Explorer

Description
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.

Script Code

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


Read a Text File into an Array

Description
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.

Script Code

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)
Loop


Read Data from a Text File

Description
Demonstration script that reads in a text file and then echoes the contents of that file.

Script Code

Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
    ("c:\scripts\ping_response.txt", ForReading)
strResponses = objTextFile.ReadAll
Wscript.Echo strResponses
objTextFile.Close


Retrieve Command Line Arguments from an Active Directory Container

Description
Demonstration scrip that retrieves the names of all the computers in an Active Directory container, and then returns service information from each of those computers.

Script Code

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


Retrieve Command Line Arguments from a Text File

Description
Demonstration script that opens a hypothetical text file consisting of server names, then retrieves service information from each on the servers in the file.

Script Code

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


Send Email from a Script

Description
Demonstration script that uses CDO to send email from a computer where the SMTP Service has been installed.

Script Code

Set objEmail = CreateObject("CDO.Message")
objEmail.From = "monitor1@fabrikam.com"
objEmail.To = "admin1@fabrikam.com"
objEmail.Subject = "Atl-dc-01 down"
objEmail.Textbody = "Atl-dc-01 is no longer accessible over the network."
objEmail.Send


Send Email without Installing the SMTP Service

Description
Demonstration script that uses CDO to send email from a computer where the SMTP Service has not been installed. Designed to work on Microsoft's corporate network.

Script Code

Set objEmail = CreateObject("CDO.Message")
objEmail.From = "admin1@fabrikam.com"
objEmail.To = "admin2@fabrikam.com"
objEmail.Subject = "Server down"
objEmail.Textbody = "Server1 is no longer accessible over the network."
objEmail.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
        "smarthost"
objEmail.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objEmail.Configuration.Fields.Update
objEmail.Send


Track Script Progress in a Command Window

Description
Demonstrates the use of StdOut as a method for indicating the progress being made by a script.

Script Code

Wscript.Echo "Processing information. This might take several minutes."
strComputer = "."
Set colServices = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2").ExecQuery _
    ("Select * from Win32_Service")
For Each objService in colServices
    Wscript.StdOut.Write(".")
Next
Wscript.StdOut.WriteLine
Wscript.Echo "Service information processed."


Track Script Progress Using Internet Explorer

Description
Demonstrates how to use Internet Explorer as a method for indicating the progress being made by a script.

Script Code

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:" _
    & "{impersonationLevel=impersonate}!\\" & 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
Wscript.Quit


Use a Text File as a Command Line Argument

Description
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.

Script Code

Set objArgs = WScript.Arguments
Const ForReading = 1
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


Write Data to a Text File

Description
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.

Script Code

Const ForAppending = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
    ("c:\scripts\service_status.txt", ForAppending, True)
Set colServices =  GetObject("winmgmts:").ExecQuery _
    ("Select * from Win32_Service")
For Each objService in colServices
    objTextFile.WriteLine(objService.DisplayName & vbTab & _
        objService.State)
objTextFile.Close


Asynchronously Enumerate Files

Description
Uses an asynchronous query to enumerate all the files on a computer. This is primarily a demonstration script; if actually run, it could take an hour or more to complete, depending on the number of files on the computer.

Script Code

Const POPUP_DURATION = 120
Const OK_BUTTON = 0
Set objWSHShell = Wscript.CreateObject("Wscript.Shell")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objSink = WScript.CreateObject("WbemScripting.SWbemSink","SINK_")
objWMIService.ExecQueryAsync objSink, "Select * from CIM_DataFile"
objPopup = objWshShell.Popup("Starting event retrieval", _
    POPUP_DURATION, "Event Retrieval", OK_BUTTON)
Sub SINK_OnObjectReady(objEvent, objAsyncContext)
    Wscript.Echo objEvent.Name
End Sub


Change File Extensions

Description
Changes the file extension for all the .log files in the C:\Scripts folder to .txt.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set FileList = objWMIService.ExecQuery _
    ("ASSOCIATORS OF {Win32_Directory.Name='c:\Scripts'} Where " _
        & "ResultClass = CIM_DataFile")
For Each objFile In FileList
    If objFile.Extension = "log" Then
        strNewName = objFile.Drive & objFile.Path & _
            objFile.FileName & "." & "txt"
        errResult = objFile.Rename(strNewName)
        Wscript.Echo errResult
    End If


Change Folder Attributes

Description
Demonstration script that uses the FileSystemObject to check if a folder is hidden and, if it is not, hides it. Script must be run on the local computer. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\FSO")
If objFolder.Attributes = objFolder.Attributes AND 2 Then
    objFolder.Attributes = objFolder.Attributes XOR 2
End If


Check the Size of a File Before Reading It

Description
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.

Script Code

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


Compress Folders

Description
Compresses the folder C:\Scripts.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFolders = objWMIService.ExecQuery _
    ("Select * from Win32_Directory where name = 'c:\\Scripts'")
For Each objFolder in colFolders
    errResults = objFolder.Compress
    Wscript.Echo errResults


Copy a File

Description
Demonstration script that uses the FileSystemObject to copy a file. Script must be run on the local computer.

Script Code

Const OverwriteExisting = True
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.CopyFile "C:\FSO\ScriptLog.txt" , "D:\Archive\", OverwriteExisting


Copy a Folder

Description
Demonstration script that uses the FileSystemObject to copy a folder to a new location. Script must be run on the local computer.

Script Code

Const OverWriteFiles = True
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.CopyFolder "C:\Scripts" , "C:\FSO" , OverWriteFiles


Copy a Set of Files

Description
Demonstration script that uses the FileSystemObject to copy all the .txt files in a folder to a new location.

Script Code

Const OverwriteExisting = True
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.CopyFile "C:\FSO\*.txt" , "D:\Archive\" , OverwriteExisting


Copy Folders Using the Shell Object

Description
Uses the Shell object to copy the folder C:\Scripts to D:\Archives. Displays the Copying Files progress dialog as the folder is being copied.

Script Code

Const FOF_CREATEPROGRESSDLG = &H0&
ParentFolder = "D:\Archive"
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(ParentFolder)
objFolder.CopyHere "C:\Scripts", FOF_CREATEPROGRESSDLG


Copy Folders Using WMI

Description
Uses WMI to copy the folder C:\Scripts to D:\Archive.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFolders = objWMIService.ExecQuery( _
    "Select * from Win32_Directory where Name = 'c:\\Scripts'")
For Each objFolder in colFolders
    errResults  = objFolder.Copy("D:\Archive")
    Wscript.Echo errResults


Create a Folder

Description
Demonstration script that uses the FileSystemObject to create a folder. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.CreateFolder("C:\FSO")


Create and Name a Text File

Description
Demonstration script that uses the FileSystemObject's GetTempName method to generate a file name, and then creates a file by that name.

Script Code

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)


Create a Network Share

Description
Creates a shared folder named FinanceShare, setting the maximum number of simultaneous connections to 25, and adding a share description.

Script Code

Const FILE_SHARE = 0
Const MAXIMUM_CONNECTIONS = 25
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objNewShare = objWMIService.Get("Win32_Share")
errReturn = objNewShare.Create _
    ("C:\Finance", "FinanceShare", FILE_SHARE, _
        MAXIMUM_CONNECTIONS, "Public share for the Finance group.")
Wscript.Echo errReturn


Create a Text File

Description
Demonstration script that creates a new, empty text file. Script must be run on the local computer.

Script Code

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


Create New Folders

Description
Uses the Shell object to create a new folder named C:\Archive.

Script Code

ParentFolder = "C:\"
set objShell = CreateObject("Shell.Application")
set objFolder = objShell.NameSpace(ParentFolder)
objFolder.NewFolder "Archive"


Delete a File

Description
Demonstration script that uses the FileSystemObject to delete a file. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.DeleteFile("C:\FSO\ScriptLog.txt")


Delete a Folder

Description
Demonstration script that uses the FileSystemObject to delete a folder. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.DeleteFolder("C:\FSO")


Delete All Files in a Folder

Description
Demonstration script that deletes all the .txt files in a folder. Script must be run on the local computer.

Script Code

Const DeleteReadOnly = True
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.DeleteFile("C:\FSO\*.txt"), DeleteReadOnly


Delete a Network Share

Description
Stops sharing a shared folder named FinanceShare. This does not delete the folder from the local hard drive, but simply stops making it available over the network.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colShares = objWMIService.ExecQuery _
    ("Select * from Win32_Share Where Name = 'FinanceShare'")
For Each objShare in colShares
    objShare.Delete


Delete a Published Folder

Description
Deletes a published folder named FinanceShare from Active Directory. This does not delete the share itself, it simply removes it from Active Directory.

Script Code

Set objContainer = GetObject("LDAP://CN=FinanceShare, " _
    & "OU=Finance, DC=fabrikam, DC=com")
objContainer.DeleteObject (0)


Delete Folders

Description
Deletes the folder C:\Scripts.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFolders = objWMIService.ExecQuery _
    ("Select * from Win32_Directory where Name = 'c:\\Scripts'")
For Each objFolder in colFolders
    errResults = objFolder.Delete
    Wscript.Echo errResults


Enumerate Administrative Tools

Description
Uses the Shell object to enumerate all the Administrative Tools installed on a computer.

Script Code

Const ADMINISTRATIVE_TOOLS = &H2f&
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(ADMINISTRATIVE_TOOLS)
Set objTools = objFolder.Items
For i = 0 to objTools.Count - 1
    Wscript.Echo objTools.Item(i)


Enumerate All the Files in a Folder

Description
Returns a list of all the files in the Scripts folder. If the computer has more than one scripts folder (for example, C:\Scripts and D:\Scripts), files will be returned from each of these folders.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService. _
    ExecQuery("Select * from CIM_DataFile where Path = '\\Scripts\\'")
For Each objFile in colFiles
    Wscript.Echo objFile.Name
Next

The System Administration Scripting Guide, part of the Windows .NET Server Resource Kit. For more information, contact scripter@microsoft.com.

Enumerate All the Files In a Folder


Enumerate All the Files on a Computer

Description
Enumerates all the files on a computer. This is primarily a demonstration script; if actually run, it could take an hour or more to complete, depending on the number of files on the computer. Depending on the number of files and on available memory, this script could fail before finishing.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
    ("Select * from CIM_Datafile")
For Each objFile in colFiles
    Wscript.Echo objFile.Name


Enumerate All the Folders on a Computer

Description
Returns a list of all the folders on a computer. This can take 15 minutes or more to complete, depending on the number of folders on the computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFolders = objWMIService.ExecQuery("Select * from Win32_Directory")
For Each objFolder in colFolders
    Wscript.Echo objFolder.Name


Enumerate a Specific Set of Files

Description
Returns a list of all the files larger than 1,000,000 bytes.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService. _
    ExecQuery("Select * from CIM_DataFile where FileSize > 1000000")
For Each objFile in colFiles
    Wscript.Echo objFile.Name & " -- " & objFile.FileSize


Enumerate a Specific Set of Folders

Description
Returns a list of all the hidden folders on a computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
    ("Select * from Win32_Directory Where Hidden = True")
For Each objFile in colFiles
    Wscript.Echo objFile.Name


Enumerate File Attributes

Description
Demonstration script that uses the FileSystemObject to enumerate the attributes of a file. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile("C:\FSO\ScriptLog.txt")
If objFile.Attributes AND 0 Then
    Wscript.Echo "No attributes set."
End If
If objFile.Attributes AND 1 Then
    Wscript.Echo "Read-only."
End If
If objFile.Attributes AND 2 Then
    Wscript.Echo "Hidden file."
End If
If objFile.Attributes AND 4 Then
    Wscript.Echo "System file."
End If
If objFile.Attributes AND 32 Then
    Wscript.Echo "Archive bit set."
End If
If objFile.Attributes AND 64 Then
    Wscript.Echo "Link or shortcut."
End If
If objFile.Attributes AND 2048 Then
    Wscript.Echo "Compressed file."
End If


Enumerate File Properties

Description
Demonstration script that uses the FileSystemObject to enumerate the properties of a file. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile("c:\windows\system32\scrrun.dll")
Wscript.Echo "Date created: " & objFile.DateCreated
Wscript.Echo "Date last accessed: " & objFile.DateLastAccessed
Wscript.Echo "Date last modified: " & objFile.DateLastModified
Wscript.Echo "Drive: " & objFile.Drive
Wscript.Echo "Name: " & objFile.Name
Wscript.Echo "Parent folder: " & objFile.ParentFolder
Wscript.Echo "Path: " & objFile.Path
Wscript.Echo "Short name: " & objFile.ShortName
Wscript.Echo "Short path: " & objFile.ShortPath
Wscript.Echo "Size: " & objFile.Size
Wscript.Echo "Type: " & objFile.Type


Enumerate Folder Attributes

Description
Demonstration script that uses the FileSystemObject to enumerate the attributes of a folder. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\FSO")
If objFolder.Attributes AND 2 Then
    Wscript.Echo "Hidden folder."
End If
If objFolder.Attributes AND 4 Then
    Wscript.Echo "System folder."
End If
If objFolder.Attributes AND 16 Then
    Wscript.Echo "Folder."
End If
If objFolder.Attributes AND 32 Then
    Wscript.Echo "Archive bit set."
End If
If objFolder.Attributes AND 2048 Then
    Wscript.Echo "Compressed folder."
End If


Enumerate Folder Properties

Description
Demonstration script that uses the FileSystemObject to enumerate the properties of a folder. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\Scripts")
Wscript.Echo "Date created: " & objFolder.DateCreated
Wscript.Echo "Date last accessed: " & objFolder.DateLastAccessed
Wscript.Echo "Date last modified: " & objFolder.DateLastModified
Wscript.Echo "Drive: " & objFolder.Drive
Wscript.Echo "Is root folder: " & objFolder.IsRootFolder
Wscript.Echo "Name: " & objFolder.Name
Wscript.Echo "Parent folder: " & objFolder.ParentFolder
Wscript.Echo "Path: " & objFolder.Path
Wscript.Echo "Short name: " & objFolder.ShortName
Wscript.Echo "Short path: " & objFolder.ShortPath
Wscript.Echo "Size: " & objFolder.Size
Wscript.Echo "Type: " & objFolder.Type


Enumerate Folders Using Dates

Description
Lists all the folders on a computer that were created after 3/1/2002.

Script Code

Const LOCAL_TIME = True
Set dtmTargetDate = CreateObject("WbemScripting.SWbemDateTime")
Set dtmConvertedDate = CreateObject("WbemScripting.SWbemDateTime")
dtmTargetDate.SetVarDate "3/1/2002", LOCAL_TIME
strComputer = "."
Set objWMIService = GetObject _
    ("winmgmts:" & "!\\" & strComputer & "\root\cimv2")
Set colFolders = objWMIService.ExecQuery _
    ("Select * from Win32_Directory Where " _
        & "CreationDate > '" & dtmTargetDate & "'")
For each objFolder in colFolders
    dtmConvertedDate.Value = objFolder.CreationDate
    Wscript.Echo objFolder.Name & VbTab & _
        dtmConvertedDate.GetVarDate(LOCAL_TIME)


Enumerate Network Shares

Description
Lists all the shared folders on a computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colShares = objWMIService.ExecQuery("Select * from Win32_Share")
For each objShare in colShares
    Wscript.Echo "AllowMaximum: " & vbTab &  objShare.AllowMaximum
    Wscript.Echo "Caption: " & vbTab &  objShare.Caption
    Wscript.Echo "MaximumAllowed: " & vbTab &  objShare.MaximumAllowed
    Wscript.Echo "Name: " & vbTab &  objShare.Name
    Wscript.Echo "Path: " & vbTab &  objShare.Path
    Wscript.Echo "Type: " & vbTab &  objShare.Type


Enumerate Published Shares

Description
Enumerates all the shared folders that have been published in Active Directory.

Script Code

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 Name, unCName, ManagedBy from " _
    & "'LDAP://DC=Fabrikam,DC=com' where objectClass='volume'"
objCommand.Properties("Timeout") = 30
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCommand.Properties("Cache Results") = False
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
Do Until objRecordSet.EOF
    Wscript.Echo "Share Name: " & objRecordSet.Fields("Name").Value
    Wscript.Echo "UNC Name: " & objRecordSet.Fields("uNCName").Value
    Wscript.Echo "Managed By: " & objRecordSet.Fields("ManagedBy").Value
    objRecordSet.MoveNext
Loop


Enumerate Special Folders

Description
Uses the Shell object to return the path to the My Pictures folder.

Script Code

Const MY_PICTURES = &H27&
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(MY_PICTURES)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Name & ": " & objFolderItem.Path


Enumerate Subfolders in a Folder

Description
Demonstration script that uses the FileSystemObject to return the folder name and size for all the subfolders in a folder. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\FSO")
Set colSubfolders = objFolder.Subfolders
For Each objSubfolder in colSubfolders
    Wscript.Echo objSubfolder.Name, objSubfolder.Size


Enumerate the Subfolders of a Folder

Description
Uses a WMI Associators of query to list all the subfolders of the folder C:\Scripts.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colSubfolders = objWMIService.ExecQuery _
    ("Associators of {Win32_Directory.Name='c:\scripts'} " _
        & "Where AssocClass = Win32_Subdirectory " _
            & "ResultRole = PartComponent")
For Each objFolder in colSubfolders
    Wscript.Echo objFolder.Name


Generate a File Name

Description
Demonstration script that uses the FileSystemObject's GetTempName method to generate random file names. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
For i = 1 to 10
    strTempFile = objFSO.GetTempName
    Wscript.Echo strTempFile


Identify Shell Object Verbs

Description
Returns a list of Shell object verbs (context menu items) for the Recycle Bin.

Script Code

Const RECYCLE_BIN = &Ha&
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(RECYCLE_BIN)
Set objFolderItem = objFolder.Self
Set colVerbs = objFolderItem.Verbs
For i = 0 to colVerbs.Count - 1
    Wscript.Echo colVerbs.Item(i)


Map All Network Shares to Local Folders

Description
Uses a WMI Associators of query to return the local path of a network share named Scripts.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colShares = objWMIService.ExecQuery _
    ("Select * From Win32_Share")
For Each objShare in colShares
    Set colAssociations = objWMIService.ExecQuery _
        ("Associators of {Win32_Share.Name='" & objShare.Name & "'} " _
            & " Where AssocClass=Win32_ShareToDirectory")
    For Each objFolder in colAssociations
        Wscript.Echo objShare.Name & vbTab & objFolder.Name
    Next


Map a Network Share to a Local Folder

Description
Uses a WMI Associators of query to return the local path of all the network shares on a computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colShares = objWMIService.ExecQuery _
    ("Associators of {Win32_Share.Name='Scripts'} Where " _
        & "AssocClass=Win32_ShareToDirectory")
For Each objFolder in colShares
    Wscript.Echo objFolder.Name


Modify a Network Share

Description
Accesses a shared folder named FinanceShare, changes the maximum number of simultaneous connections to 50, and provides a new share description.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colShares = objWMIService.ExecQuery _
    ("Select * from Win32_Share Where Name = 'FinanceShare'")
For Each objShare in colShares
    errReturn = objShare.SetShareInfo(50, _
        "Public share for HR administrators and the Finance Group.")
Wscript.Echo errReturn


Modify File Attributes

Description
Demonstration script that checks to see if a file is read-only and, if it is not, marks it as read-only. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile("C:\FSO\TestScript.vbs")
If objFile.Attributes = objFile.Attributes AND 1 Then
    objFile.Attributes = objFile.Attributes XOR 1
End If


Monitor File Creation

Description
Temporary event consumer that issues an alert any time a file is created in the C:\Scripts folder. Best when run under Cscript.exe.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & _
        strComputer & "\root\cimv2")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
    ("SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE " _
        & "Targetinstance ISA 'CIM_DirectoryContainsFile' and " _
            & "TargetInstance.GroupComponent= " _
                & "'Win32_Directory.Name=""c:\\\\scripts""'")
Do
    Set objLatestEvent = colMonitoredEvents.NextEvent
    Wscript.Echo objLatestEvent.TargetInstance.PartComponent
Loop


Monitor File Deletion

Description
Temporary event consumer that issues an alert any time a file is deleted from the C:\Scripts folder. Best when run under Cscript.exe.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & _
        strComputer & "\root\cimv2")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
    ("SELECT * FROM __InstanceDeletionEvent WITHIN 10 WHERE " _
        & "Targetinstance ISA 'CIM_DirectoryContainsFile' and " _
            & "TargetInstance.GroupComponent= " _
                & "'Win32_Directory.Name=""c:\\\\scripts""'")
Do
    Set objLatestEvent = colMonitoredEvents.NextEvent
    Wscript.Echo objLatestEvent.TargetInstance.PartComponent
Loop


Monitor File Modification

Description
Temporary event consumer that issues an alert any time the file C:\Scripts\Index.vbs is modified. Best when run under Cscript.exe.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & _
        strComputer & "\root\cimv2")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
    ("SELECT * FROM __InstanceModificationEvent WITHIN 10 WHERE " _
        & "TargetInstance ISA 'CIM_DataFile' and " _
            & "TargetInstance.Name='c:\\scripts\\index.vbs'")
Do
    Set objLatestEvent = colMonitoredEvents.NextEvent
    Wscript.Echo "File: " & objLatestEvent.TargetInstance.Name
    Wscript.Echo "New size: " & objLatestEvent.TargetInstance.FileSize
    Wscript.Echo "Old size: " & objLatestEvent.PreviousInstance.FileSize
Loop


Move a File

Description
Demonstration script that uses the FileSystermObject to move a file from one location to another. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.MoveFile "C:\FSO\ScriptLog.log" , "D:\Archive"


Move a Folder

Description
Demonstration script that uses the FileSystermObject to move a folder from one location to another. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.MoveFolder "C:\Scripts" , "\\helpdesk\management"


Move a Set of Files

Description
Demonstration script that uses the FileSystemObject to move all the .txt files in a folder to a new location. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.MoveFile "C:\FSO\*.txt" , "D:\Archive\"


Move Files

Description
Moves all the Windows Media (.wma) files to the folder C:\Media Archive.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService. _
    ExecQuery("Select * from CIM_DataFile where Extension = 'wma'")
For Each objFile in colFiles
    strCopy = "C:\Media Archive\" & objFile.FileName _
        & "." & objFile.Extension
    objFile.Copy(strCopy)
    objFile.Delete


Move Folders Using the Shell Object

Description
Uses the Shell object to move the folder C:\Scripts to D:\Archives. Displays the Copying Files progress dialog as the folder is being moved.

Script Code

Const FOF_CREATEPROGRESSDLG = &H0&
TargetFolder = "D:\Archive"
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(TargetFolder)
objFolder.MoveHere "C:\Scripts", FOF_CREATEPROGRESSDLG


Move Folders Using WMI

Description
Uses WMI to move the folder C:\Scripts to C:\Admins\Documents\Archive\VBScript.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFolders = objWMIService.ExecQuery _
    ("Select * from Win32_Directory where name = 'c:\\Scripts'")
For Each objFolder in colFolders
    errResults = objFolder.Rename("C:\Admins\Documents\Archive\VBScript")
    Wscript.Echo errResults


Parse a Path Name

Description
Demonstration script that uses the FileSystemObject to return pathname information for a while, including file name, file extension, complete file path, etc. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile("ScriptLog.txt")
Wscript.Echo "Absolute path: " & objFSO.GetAbsolutePathName(objFile)
Wscript.Echo "Parent folder: " & objFSO.GetParentFolderName(objFile)
Wscript.Echo "File name: " & objFSO.GetFileName(objFile)
Wscript.Echo "Base name: " & objFSO.GetBaseName(objFile)
Wscript.Echo "Extension name: " & objFSO.GetExtensionName(objFile)


Perform Actions on Files

Description
Uses the Shell object to print all the files in the C:\Logs folder.

Script Code

TargetFolder = "C:\Logs"
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(TargetFolder)
Set colItems = objFolder.Items
For i = 0 to colItems.Count - 1
    colItems.Item(i).InvokeVerbEx("Print")


Publish a Shared Folder

Description
Publishes a shared folder in Active Directory, assigning the folder a description and three keywords.

Script Code

Set objComputer = GetObject _
    ("LDAP://OU=Finance, DC=fabrikam, DC=com")
Set objShare = objComputer.Create("volume", "CN=FinanceShare")
objShare.Put "uNCName", "\\atl-dc-02\FinanceShare"
objShare.Put "Description", "Public share for users in the Finance group."
objShare.Put "Keywords", Array("finance", "fiscal", "monetary")
objShare.SetInfo


Read a Text File Character by Character

Description
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.

Script Code

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


Read a Text File from the Bottom Up

Description
Demonstration script that uses the FileSystemObject to read a text file, and then to echo the text file in inverse order (that is, beginning with the last line in the text file and ending with the first line).

Script Code

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)


Rename a File

Description
Demonstration script that uses the FileSystemObject to rename a file. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.MoveFile "C:\FSO\ScriptLog.txt" , "C:\FSO\BackupLog.txt"


Rename a Folder

Description
Demonstration script that uses the FileSystemObject to rename a folder. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.MoveFolder "C:\FSO\Samples" , "C:\FSO\Scripts"


Rename Files

Description
Renames the file C:\Scripts\Toggle_Service.vbs to C:\Scripts\Toggle_Service.old.

Script Code

strComputer = "."
Set objWMIService = GetObject _
    ("winmgmts:" & "!\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
    ("Select * from Cim_Datafile where Name = " _
        & "'c:\\scripts\\toggle_service.vbs'")
For Each objFile in colFiles
    errResult = objFile.Rename("c:\scripts\toggle_service.old")
    Wscript.Echo errResult


Rename Folders

Description
Renames the folder C:\Scripts to C:\Repository.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFolders = objWMIService.ExecQuery _
    ("Select * from Win32_Directory where name = 'c:\\Scripts'")
For Each objFolder in colFolders
    errResults = objFolder.Rename("C:\Script Repository")
    Wscript.Echo errResults


Retrieve Detailed Summary Information for a File

Description
Uses the Shell's Application object to retrieve detailed summary information including name, size, owner, and file attributes) for all the files in a folder.

Script Code

Set objShell = CreateObject ("Shell.Application")
Set objFolder = objShell.Namespace ("C:\Scripts")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim arrHeaders(13)
For i = 0 to 13
    arrHeaders(i) = objFolder.GetDetailsOf (objFolder.Items, i)
Next
For Each strFileName in objFolder.Items
    For i = 0 to 13
        If i <> 9 then
            Wscript.echo arrHeaders(i) _
                & ": " & objFolder.GetDetailsOf (strFileName, i)
        End If
    Next
    Wscript.Echo


Retrieve Extended File Properties

Description
Uses the Shell object to return extended properties for all the files in the folder C:\Scripts.

Script Code

Dim arrHeaders(34)
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace("C:\Scripts")
For i = 0 to 33
    arrHeaders(i) = objFolder.GetDetailsOf(objFolder.Items, i)
Next
For Each strFileName in objFolder.Items
    For i = 0 to 33
        Wscript.echo i & vbtab & arrHeaders(i) _
            & ": " & objFolder.GetDetailsOf(strFileName, i)
    Next


Retrieve File Properties

Description
Lists the properties for the file C:\Scripts\Adsi.vbs.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
    ("Select * from CIM_Datafile Where name = 'c:\\Scripts\\Adsi.vbs'")
For Each objFile in colFiles
    Wscript.Echo "Access mask: " & objFile.AccessMask
    Wscript.Echo "Archive: " & objFile.Archive
    Wscript.Echo "Compressed: " & objFile.Compressed
    Wscript.Echo "Compression method: " & objFile.CompressionMethod
    Wscript.Echo "Creation date: " & objFile.CreationDate
    Wscript.Echo "Computer system name: " & objFile.CSName
    Wscript.Echo "Drive: " & objFile.Drive
    Wscript.Echo "8.3 file name: " & objFile.EightDotThreeFileName
    Wscript.Echo "Encrypted: " & objFile.Encrypted
    Wscript.Echo "Encryption method: " & objFile.EncryptionMethod
    Wscript.Echo "Extension: " & objFile.Extension
    Wscript.Echo "File name: " & objFile.FileName
    Wscript.Echo "File size: " & objFile.FileSize
    Wscript.Echo "File type: " & objFile.FileType
    Wscript.Echo "File system name: " & objFile.FSName
    Wscript.Echo "Hidden: " & objFile.Hidden
    Wscript.Echo "Last accessed: " & objFile.LastAccessed
    Wscript.Echo "Last modified: " & objFile.LastModified
    Wscript.Echo "Manufacturer: " & objFile.Manufacturer
    Wscript.Echo "Name: " & objFile.Name
    Wscript.Echo "Path: " & objFile.Path
    Wscript.Echo "Readable: " & objFile.Readable
    Wscript.Echo "System: " & objFile.System
    Wscript.Echo "Version: " & objFile.Version
    Wscript.Echo "Writeable: " & objFile.Writeable


Retrieve File Version Information

Description
Demonstration script that uses the FileSystemObject to retrieve the file version for a .dll file. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
Wscript.Echo objFSO.GetFileVersion("c:\windows\system32\scrrun.dll")


Retrieve Folder Properties

Description
Lists the properties of the folder C:\Scripts.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFolders = objWMIService. _
    ExecQuery("Select * from Win32_Directory where name = 'c:\\Scripts'")
For Each objFolder in colFolders
    Wscript.Echo "Archive: " & objFolder.Archive
    Wscript.Echo "Caption: " & objFolder.Caption
    Wscript.Echo "Compressed: " & objFolder.Compressed
    Wscript.Echo "Compression method: " & objFolder.CompressionMethod
    Wscript.Echo "Creation date: " & objFolder.CreationDate
    Wscript.Echo "Encrypted: " & objFolder.Encrypted
    Wscript.Echo "Encryption method: " & objFolder.EncryptionMethod
    Wscript.Echo "Hidden: " & objFolder.Hidden
    Wscript.Echo "In use count: " & objFolder.InUseCount
    Wscript.Echo "Last accessed: " & objFolder.LastAccessed
    Wscript.Echo "Last modified: " & objFolder.LastModified
    Wscript.Echo "Name: " & objFolder.Name
    Wscript.Echo "Path: " & objFolder.Path
    Wscript.Echo "Readable: " & objFolder.Readable
    Wscript.Echo "System: " & objFolder.System
    Wscript.Echo "Writeable: " & objFolder.Writeable


Retrieve Summary Information for a File

Description
Uses the Shell's Application object to retrieve the file name for all the files in a folder.

Script Code

Const FILE_NAME = 0
Set objShell = CreateObject ("Shell.Application")
Set objFolder = objShell.Namespace ("C:\Scripts")
For Each strFileName in objFolder.Items
    Wscript.Echo "File name: " & objFolder.GetDetailsOf _
        (strFileName, FILE_NAME)


Return a Disk Drive Collection

Description
Demonstration script that uses the FileSystemObject to return a list of all the disk drives installed on a computer. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set colDrives = objFSO.Drives
For Each objDrive in colDrives
    Wscript.Echo "Drive letter: " & objDrive.DriveLetter


Search for Published Folders

Description
Searches Active Directory for any shared folders that have the keyword "finance."

Script Code

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 Name, unCName, ManagedBy from "
    & "'LDAP://DC=Reskit,DC=com'" _
        & " where objectClass='volume' and Keywords = 'finance*'"
objCommand.Properties("Timeout") = 30
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCommand.Properties("Cache Results") = False
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
Do Until objRecordSet.EOF
    Wscript.Echo "Share Name: " & objRecordSet.Fields("Name").Value
    Wscript.Echo "UNC Name: " & objRecordSet.Fields("uNCName").Value
    Wscript.Echo "Managed By: " & objRecordSet.Fields("ManagedBy").Value
    objRecordSet.MoveNext
Loop


Uncompress Folders

Description
Uncompresses the folder C:\Scripts.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFolders = objWMIService.ExecQuery _
    ("Select * from Win32_Directory where name = 'c:\\Scripts'")
For Each objFolder in colFolders
    errResults = objFolder.Uncompress
    Wscript.Echo errResults


Use Recursion to Enumerate Subfolders

Description
Demonstration script that uses the FileSystemObject to recursively list all the subfolders (and their subfolders) within a folder. Script must be run on the local computer.

Script Code

Set FSO = CreateObject("Scripting.FileSystemObject")
ShowSubfolders FSO.GetFolder("C:\Scripts")
Sub ShowSubFolders(Folder)
    For Each Subfolder in Folder.SubFolders
        Wscript.Echo Subfolder.Path
        ShowSubFolders Subfolder
End Sub


Use the Browse for Folder Dialog Box

Description
Uses the Shell object to display the Browse for Folder dialog box. After a folder has been selected, the script reports whether or not the folder is read-only.

Script Code

Const WINDOW_HANDLE = 0
Const NO_OPTIONS = 0
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder _
    (WINDOW_HANDLE, "Select a folder:", NO_OPTIONS, "C:\Scripts")
Set objFolderItem = objFolder.Self
objPath = objFolderItem.Path
objPath = Replace(objPath, "\", "\\")
strComputer = "."
Set objWMIService = GetObject _
    ("winmgmts:" & "!\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
    ("Select * from Win32_Directory where name = '" & objPath & "'")
For Each objFile in colFiles
    Wscript.Echo "Readable: " & objFile.Readable


Use Wildcards in a Folder Query

Description
Returns a list of all the folders whose path begins with C:\S. This script runs only under Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFolders = objWMIService.ExecQuery _
    ("Select * from Win32_Directory where Name Like '%c:\\S%'")
For Each objFolder in colFolders
    Wscript.Echo "Name: " & objFolder.Name


Use Wildcards in File Queries

Description
Returns a list of all the files whose name beings with a tilde (~). This script runs only under Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & _
        strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
    ("Select * from CIM_DataFile where FileName Like '%~%'")
For Each objFile in colFiles
    Wscript.Echo objFile.Name


Verify that a File Exists

Description
Demonstration script that uses the FileSystemObject to verify that a file exists. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists("C:\FSO\ScriptLog.txt") Then
    Set objFolder = objFSO.GetFile("C:\FSO\ScriptLog.txt")
Else
    Wscript.Echo "File does not exist."
End If


Verify that a Folder Exists

Description
Demonstration script that uses the FileSystemObject to verify that a folder exists. If the folder does exist, the script binds to that folder. Script must be run on the local computer.

Script Code

Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists("C:\FSO") Then
    Set objFolder = objFSO.GetFolder("C:\FSO")
Else
    Wscript.Echo "Folder does not exist.”
End If


Add a Support URL to an Event Log Entry

Description
Writes an event to the Application event log that includes a support URL. Requires Windows XP or Windows .NET Server.

Script Code

Const EVENT_FAILED = 1
Set objShell = Wscript.CreateObject("Wscript.Shell")
objShell.LogEvent EVENT_FAILED, _
    "Payroll application could not be installed." _
    & "Additional information is available from http://www.fabrikam.com."


Add WMI Data to an Event Log Entry

Description
Writes an event that includes additional information such as user name and the amount of free disk space on the computer.

Script Code

Const EVENT_FAILED = 2
Set objShell = Wscript.CreateObject("Wscript.Shell")
Set objNetwork = Wscript.CreateObject("Wscript.Network")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDiskDrives = objWMIService.ExecQuery _
    ("Select * from win32_perfformatteddata_perfdisk_logicaldisk")
For each objDisk in colDiskDrives
    strDriveSpace = objDisk.Name & " " & objDisk.FreeMegabytes _
        & VbCrLf
Next
strEventDescription = "Payroll application could not be installed on " _
    & objNetwork.UserDomain & "\" & objNetwork.ComputerName _
        & " by user " & objNetwork.UserName & _
            ". Free space on each drive is: " & strDriveSpace
objShell.LogEvent EVENT_FAILED, strEventDescription


Asynchronous Event Log Query

Description
Uses an asynchronous query to retrieve all the events recorded in all the event logs. This approach is faster than retrieving a large number of events using a synchronous query.

Script Code

Const POPUP_DURATION = 10
Const OK_BUTTON = 0
Set objWSHShell = Wscript.CreateObject("Wscript.Shell")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objSink = WScript.CreateObject("WbemScripting.SWbemSink","SINK_")
objWMIService.InstancesOfAsync objSink, "Win32_NTLogEvent"
Error = objWshShell.Popup("Starting event retrieval", POPUP_DURATION, _
    "Event Retrieval", OK_BUTTON)
Sub SINK_OnCompleted(iHResult, objErrorObject, objAsyncContext)
    WScript.Echo "Asynchronous operation is done."
End Sub
Sub SINK_OnObjectReady(objEvent, objAsyncContext)
    Wscript.Echo "Category: " & objEvent.Category
    Wscript.Echo "Computer Name: " & objEvent.ComputerName
    Wscript.Echo "Event Code: " & objEvent.EventCode
    Wscript.Echo "Message: " & objEvent.Message
    Wscript.Echo "Record Number: " & objEvent.RecordNumber
    Wscript.Echo "Source Name: " & objEvent.SourceName
    Wscript.Echo "Time Written: " & objEvent.TimeWritten
    Wscript.Echo "Event Type: " & objEvent.Type
    Wscript.Echo "User: " & objEvent.User
End Sub


Backup and Clear an Event Log

Description
Backs up and clears the Application event log.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate,(Backup)}!\\" & _
        strComputer & "\root\cimv2")
Set colLogFiles = objWMIService.ExecQuery _
    ("Select * from Win32_NTEventLogFile where LogFileName='Application'")
For Each objLogfile in colLogFiles
    errBackupLog = objLogFile.BackupEventLog("c:\scripts\application.evt")
    If errBackupLog <> 0 Then
        Wscript.Echo "The Application event log could not be backed up."
    Else
        objLogFile.ClearEventLog()
    End If


Backup and Clear Large Event Logs

Description
Backs up and clears am event log if the log file size is larger than 20 megabytes.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate, (Backup, Security)}!\\" _
        & strComputer & "\root\cimv2")
Set colLogFiles = objWMIService.ExecQuery _
    ("Select * from Win32_NTEventLogFile")
For each objLogfile in colLogFiles
    If objLogFile.FileSize > 100000 Then
       strBackupLog = objLogFile.BackupEventLog _
           ("c:\scripts\" & objLogFile.LogFileName & ".evt")
       objLogFile.ClearEventLog()
    End If


Configure Event Log Properties

Description
Sets the maximum size of all event logs to 250 megabytes, and enables the log to overwrite any events older than 14 days.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate,(Security)}!\\" & _
        strComputer & "\root\cimv2")
Set colLogFiles = objWMIService.ExecQuery _
    ("Select * from Win32_NTEventLogFile")
For each objLogfile in colLogFiles
    strLogFileName = objLogfile.Name
    Set wmiSWbemObject = GetObject _
        ("winmgmts:{impersonationLevel=Impersonate}!\\.\root\cimv2:" _
            & "Win32_NTEventlogFile.Name='" & strLogFileName & "'")
    wmiSWbemObject.MaxFileSize = 2500000000
    wmiSWbemObject.OverwriteOutdated = 14
    wmiSWbemObject.Put_


Copy Event Log Events to a Database

Description
Retrieves events from all the event logs and records these in a database with the DSN Name EventLogs.

Script Code

Set objConn = CreateObject("ADODB.Connection")
Set objRS = CreateObject("ADODB.Recordset")
objConn.Open "DSN=EventLogs;"
objRS.CursorLocation = 3
objRS.Open "SELECT * FROM EventTable" , objConn, 3, 3
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colRetrievedEvents = objWMIService.ExecQuery _
    ("Select * from Win32_NTLogEvent")
For Each objEvent in colRetrievedEvents
    objRS.AddNew
    objRS("Category") = objEvent.Category
    objRS("ComputerName") = objEvent.ComputerName
    objRS("EventCode") = objEvent.EventCode
    objRS("Message") = objEvent.Message
    objRS("RecordNumber") = objEvent.RecordNumber
    objRS("SourceName") = objEvent.SourceName
    objRS("TimeWritten") = objEvent.TimeWritten
    objRS("Type") = objEvent.Type
    objRS("User") = objEvent.User
    objRS.Update
Next
objRS.Close
objConn.Close


Copy Previous Days Event Log Events to a Database

Description
Retrieves events from all the event logs that were recorded on the previous day, and writes these records to a database with the DSN Name EventLogs. Requires Windows XP or Windows .NET Server.

Script Code

Set objConn = CreateObject("ADODB.Connection")
Set objRS = CreateObject("ADODB.Recordset")
objConn.Open "DSN=EventLogs;"
objRS.CursorLocation = 3
objRS.Open "SELECT * FROM EventTable" , objConn, 3, 3
Set dtmStartDate = CreateObject("WbemScripting.SWbemDateTime")
Set dtmEndDate = CreateObject("WbemScripting.SWbemDateTime")
DateToCheck = Date - 1
dtmEndDate.SetVarDate Date, True
dtmStartDate.SetVarDate DateToCheck, True
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colEvents = objWMIService.ExecQuery _
    ("Select * from Win32_NTLogEvent Where TimeWritten >= '" _
        & dtmStartDate & "' and TimeWritten < '" & dtmEndDate & "'")
For each objEvent in colEvents
    objRS.AddNew
    objRS("Category") = objEvent.Category
    objRS("ComputerName") = objEvent.ComputerName
    objRS("EventCode") = objEvent.EventCode
    objRS("Message") = objEvent.Message
    objRS("RecordNumber") = objEvent.RecordNumber
    objRS("SourceName") = objEvent.SourceName
    objRS("TimeWritten") = objEvent.TimeWritten
    objRS("Type") = objEvent.Type
    objRS("User") = objEvent.User
    objRS.Update
Next
objRS.Close
objConn.Close


Create a Custom Event Log

Description
Creates a custom event log named Scripts.

Script Code

Const NO_VALUE = Empty
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.RegWrite "HKLM\System\CurrentControlSet\Services\EventLog\Scripts\", _
    NO_VALUE


Event Log Properties

Description
Retrieves a list of properties for all the event logs on a computer, except the Security event log.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objInstalledLogFiles = objWMIService.ExecQuery _
    ("Select * from Win32_NTEventLogFile")
For each objLogfile in objInstalledLogFiles
    Wscript.Echo "Name: " &  objLogfile.LogFileName
    Wscript.Echo "Maximum Size: " &  objLogfile.MaxFileSize
    If objLogfile.OverWriteOutdated > 365 Then
        Wscript.Echo "Overwrite Outdated Records: Never." & VbCrLf
    ElseIf objLogfile.OverWriteOutdated = 0 Then
        Wscript.Echo "Overwrite Outdated Records: As needed." & VbCrLf
    Else
        Wscript.Echo "Overwrite Outdated Records After: " &  _
            objLogfile.OverWriteOutdated & " days" & VbCrLf
    End If


Parse a Comma Separated Values Log

Description
Extracts the information in the DHCP Server log to individual fields and records.

Script Code

Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("C:\Windows\System32\DHCP\" _
    & "DhcpSrvLog-Mon.log", ForReading)
Do While objTextFile.AtEndOfStream <> True
    If inStr(objtextFile.Readline, ",") Then
        arrDHCPRecord = split(objTextFile.Readline, ",")
        wscript.echo "Event ID: " & arrDHCPRecord(0)
        wscript.echo "Date: " & arrDHCPRecord(1)
        wscript.echo "Time: " & arrDHCPRecord(2)
        wscript.echo "Description: " & arrDHCPRecord(3)
        wscript.echo "IP Address: " & arrDHCPRecord(4)
        wscript.echo "Host Name: " & arrDHCPRecord(5)
        wscript.echo "MAC Address: " & arrDHCPRecord(6)
    Else
        objTextFile.Skipline
    End If
    i = i + 1
Loop


Parse a Fixed Width Column Log

Description
Extracts the information in the NetSetup log to individual fields and records.

Script Code

Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("C:\Windows\Debug\Netsetup.log", _
    ForReading)
Do While objTextFile.AtEndOfStream <> True
    strLinetoParse = objTextFile.ReadLine
    dtmEventDate = Mid(strLinetoParse, 1, 6)
    dtmEventTime = Mid(strLinetoParse, 7, 9)
    strEventDescription = Mid(strLinetoParse, 16)
    Wscript.Echo "Date: " & dtmEventDate
    Wscript.Echo "Time: " & dtmEventTime
    Wscript.Echo "Description: " & strEventDescription & VbCrLf
Loop
objFSO.Close


Query a Specific Event Log

Description
Retrieves all the events from the System event log.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colLoggedEvents = objWMIService.ExecQuery _
    ("Select * from Win32_NTLogEvent Where Logfile = 'Application'")
For Each objEvent in colLoggedEvents
    Wscript.Echo "Category: " & objEvent.Category
    Wscript.Echo "Computer Name: " & objEvent.ComputerName
    Wscript.Echo "Event Code: " & objEvent.EventCode
    Wscript.Echo "Message: " & objEvent.Message
    Wscript.Echo "Record Number: " & objEvent.RecordNumber
    Wscript.Echo "Source Name: " & objEvent.SourceName
    Wscript.Echo "Time Written: " & objEvent.TimeWritten
    Wscript.Echo "Event Type: " & objEvent.Type
    Wscript.Echo "User: " & objEvent.User


Retrieve All Events from an Event Log

Description
Retrieves all the events from all the event logs on a computer. Note: This is primarily a demonstration script. It can take several hours, or more, to run, depending on the number of events recorded in your event logs.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colLoggedEvents = objWMIService.ExecQuery _
    ("Select * from Win32_NTLogEvent Where Logfile = 'Application'")
For Each objEvent in colLoggedEvents
    Wscript.Echo "Category: " & objEvent.Category
    Wscript.Echo "Computer Name: " & objEvent.ComputerName
    Wscript.Echo "Event Code: " & objEvent.EventCode
    Wscript.Echo "Message: " & objEvent.Message
    Wscript.Echo "Record Number: " & objEvent.RecordNumber
    Wscript.Echo "Source Name: " & objEvent.SourceName
    Wscript.Echo "Time Written: " & objEvent.TimeWritten
    Wscript.Echo "Event Type: " & objEvent.Type
    Wscript.Echo "User: " & objEvent.User


Retrieve Specific Events from an Event Log

Description
Retrieves all events with an event code of 6008 from the System event log.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colLoggedEvents = objWMIService.ExecQuery _
        ("Select * from Win32_NTLogEvent Where Logfile = 'System' and " _
            & "EventCode = '6008'")
Wscript.Echo "Improper shutdowns: " & colLoggedEvents.Count


Retrieve Events For One Day From An Event Log

Description
Retrieves all the events recorded on a specific date from all the event logs.

Script Code

Const CONVERT_TO_LOCAL_TIME = True
Set dtmStartDate = CreateObject("WbemScripting.SWbemDateTime")
Set dtmEndDate = CreateObject("WbemScripting.SWbemDateTime")
DateToCheck = CDate("2/18/2002")
dtmStartDate.SetVarDate DateToCheck, CONVERT_TO_LOCAL_TIME
dtmEndDate.SetVarDate DateToCheck + 1, CONVERT_TO_LOCAL_TIME
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colEvents = objWMIService.ExecQuery _
    ("Select * from Win32_NTLogEvent Where TimeWritten >= '" _
        & dtmStartDate & "' and TimeWritten < '" & dtmEndDate & "'")
For each objEvent in colEvents
    Wscript.Echo "Category: " & objEvent.Category
    Wscript.Echo "Computer Name: " & objEvent.ComputerName
    Wscript.Echo "Event Code: " & objEvent.EventCode
    Wscript.Echo "Message: " & objEvent.Message
    Wscript.Echo "Record Number: " & objEvent.RecordNumber
    Wscript.Echo "Source Name: " & objEvent.SourceName
    Wscript.Echo "Time Written: " & objEvent.TimeWritten
    Wscript.Echo "Event Type: " & objEvent.Type
    Wscript.Echo "User: " & objEvent.User
    Wscript.Echo objEvent.LogFile


Security Log Properties

Description
Retrieves properties for the Security event log.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate,(Security)}!\\" & _
        strComputer & "\root\cimv2")
Set colLogFiles = objWMIService.ExecQuery _
    ("Select * from Win32_NTEventLogFile where LogFileName='Security'")
For Each objLogFile in colLogFiles
    Wscript.Echo objLogFile.NumberOfRecords
    Wscript.Echo "Maximum Size: " &  objLogfile.MaxFileSize


System Event Log Properties

Description
Reports the number of events currently recorded in the System event log.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colLogFiles = objWMIService.ExecQuery _
    ("Select * from Win32_NTEventLogFile where LogFileName='System'")
For Each objLogFile in colLogFiles
    Wscript.Echo objLogFile.NumberOfRecords


Create Unique File Names for Event Log Backups

Description
Backs up and clears the Application event log, generating a unique file name for each backup based on the current date.

Script Code

dtmThisDay = Day(Date)
dtmThisMonth = Month(Date)
dtmThisYear = Year(Date)
strBackupName = dtmThisYear & "_" & dtmThisMonth & "_" & dtmThisDay
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate,(Backup)}!\\" & _
        strComputer & "\root\cimv2")
Set colLogFiles = objWMIService.ExecQuery _
    ("Select * from Win32_NTEventLogFile where LogFileName='Application'")
For Each objLogfile in colLogFiles
    objLogFile.BackupEventLog("c:\scripts\" & strBackupName & _
        "_application.evt")
    objLogFile.ClearEventLog()


Write Events to a Remote Event Log

Description
Writes an event to the Application event log on a remote computer named PrimaryServer.

Script Code

Const EVENT_SUCCESS = 0
Set objShell = Wscript.CreateObject("Wscript.Shell")
objShell.LogEvent EVENT_SUCCESS, _
    "Payroll application successfully installed." , "\\PrimaryServer"


Write Events to the Local Event Log

Description
Writes an event to the Application event log on the local computer.

Script Code

Const EVENT_SUCCESS = 0
Set objShell = Wscript.CreateObject("Wscript.Shell")
objShell.LogEvent EVENT_SUCCESS, _
    "Payroll application successfully installed."


Write to a Custom Event Log Using EventCreate

Description
Uses the EventCreate.exe utility to write an event to a custom event log named Scripts. Requires Windows XP or Windows .NET Server.

Script Code

Set WshShell = WScript.CreateObject("WScript.Shell")
strCommand = "eventcreate /T Error /ID 100 /L Scripts /D " & _
    Chr(34) & "Test event." & Chr(34)
WshShell.Run strcommand


Baseline Performance Monitoring

Description
Uses cooked performance counters and the SWbemRefresher object to monitor three performance counters on a computer, and save that data to a text file. Requires Windows XP or Windows .NET Server.

Script Code

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
objLogFile.Close


Configure Trust Relationship Properties

Description
Configures trust relationship refresh and validation properties. Requires Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & _
        strComputer & "\root\MicrosoftActiveDirectory")
Set colTrustList = objWMIService.ExecQuery _
    ("Select * from Microsoft_TrustProvider")
For Each objTrust in colTrustList
    objTrust.TrustListLifetime = 25
    objTrust.TrustStatusLifetime = 10
    objTrust.TrustCheckLevel = 1
    objTrust.Put_


Create a Permanent Event Consumer

Description
Creates a permanent event consumer for monitoring changes in service status.

Script Code

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_


Create a Permanent Event Filter

Description
Creates a permanent event filter for monitoring changes in service status.

Script Code

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_


Display Real Time Events in a Command Window

Description
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.

Script Code

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


Enumerate Active Directory Database Replication Partners

Description
Returns a list of Active Directory replication partners for a domain controller. Requires Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & _
        strComputer & "\root\MicrosoftActiveDirectory")
Set colReplicationOperations = objWMIService.ExecQuery _
    ("Select * from MSAD_ReplNeighbor")
For each objReplicationJob in colReplicationOperations
    Wscript.Echo objReplicationJob.Domain
    Wscript.Echo objReplicationJob.NamingContextDN
    Wscript.Echo objReplicationJob.SourceDsaDN
    Wscript.Echo objReplicationJob.LastSyncResult
    Wscript.Echo objReplicationJob.NumConsecutiveSyncFailures


Enumerate Domain Information for Trust Partners

Description
Returns local domain information. Requires Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & _
        strComputer & "\root\MicrosoftACtiveDirectory")
Set colDomainInfo = objWMIService.ExecQuery _
    ("Select * from Microsoft_LocalDOmainInfo")
For each objDomain in colDomainInfo
    Wscript.Echo objDomain.DNSName
    Wscript.Echo objDomain.FlatName
    Wscript.Echo objDomain.SID
    Wscript.Echo objDomain.TreeName
    Wscript.Echo objDomain.DCName


Enumerate Trust Relationships

Description
Enumerates trust relationships. Requires Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & _
        strComputer & "\root\MicrosoftActiveDirectory")
Set colTrustList = objWMIService.ExecQuery _
    ("Select * from Microsoft_DomainTrustStatus")
For each objTrust in colTrustList
    Wscript.Echo objTrust.TrustedDomain
    Wscript.Echo objTrust.TrustDirection
    Wscript.Echo objTrust.TrustType
    Wscript.Echo objTrust.TrustAttributes
    Wscript.Echo objTrust.TrustedDCName
    Wscript.Echo objTrust.TrustStatus
    Wscript.Echo objTrust.TrustIsOK


Install Active Directory Database Performance Counters

Description
Installs the Active Database performance counters on a domain controller.

Script Code

Set WshShell = WScript.CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("Shell.Application")
objFSO.CreateFolder ("C:\Performance")
Set objCopyFile = objFSO.GetFile("C:\windows\system32\esentprf.dll ")
objCopyFile.Copy ("C:\performance\esentprf.dll ")
WshShell.RegWrite _
    "HKLM\System\CurrentControlSet\Services\Esent\Performance\Open", _
        "OpenPerformanceData", "REG_SZ"
WshShell.RegWrite _
    "HKLM\System\CurrentControlSet\Services\Esent\Performance\Collect", _
        "CollectPerformanceData", "REG_SZ"
WshShell.RegWrite _
    "HKLM\System\CurrentControlSet\Services\Esent\Performance\Close", _
        "ClosePerformanceData", "REG_SZ"
WshShell.RegWrite _
    "HKLM\System\CurrentControlSet\Services\Esent\Performance\Library", _
        "C:\Performance\Esentprf.dll", "REG_SZ"
strCommandText = "%comspec% /c lodctr.exe c:\windows\system32\esentprf.ini"
WshShell.Run strCommandText


Monitor Active Directory Database Performance

Description
Uses cooked performance counters to monitor the performance of the Active Directory database on a domain controller. Requires Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDatabases = objWMIService.ExecQuery _
    ("Select * from Win32_PerfFormattedData_Esent_Database " _
        & "Where Name = 'NT Directory'")
For Each objADDatabase in colDatabases
    Wscript.Echo objADDatabase.DatabaseCachePercentHit


Monitor Active Directory Replication

Description
Returns a list of pending replication jobs on a domain controller. Requires Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & _
        strComputer & "\root\MicrosoftActiveDirectory")
Set colReplicationOperations = objWMIService.ExecQuery _
        ("Select * from MSAD_ReplPendingOp")
If colReplicationOperations.Count = 0 Then
    Wscript.Echo "There are no replication jobs pending."
    Wscript.Quit
Else
    For each objReplicationJob in colReplicationOperations
        Wscript.Echo objReplicationJob.SerialNumber
        Wscript.Echo objReplicationJob.TimeEnqueued
        Wscript.Echo objReplicationJob.DsaDN
        Wscript.Echo objReplicationJob.DsaAddress
        Wscript.Echo objReplicationJob.NamingContextDn
End If


Monitor Available Memory

Description
Issues an alert if available memory on a computer falls below 4 megabytes. Requires Windows XP or Windows .NET Server.

Script Code

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
objRefresher.Refresh
Do
    For each intAvailableBytes in objMemory
        If intAvailableBytes.AvailableMBytes < 4 Then
            Wscript.Echo "Available memory has fallen below 4 megabytes."
        End If
    Next
    objRefresher.Refresh
Loop


Monitor Computer Availability

Description
Uses the Win32_PingStatus class to verify that a computer is accessible over the network. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPingedComputers = objWMIService.ExecQuery _
    ("Select * from Win32_PingStatus Where Address = '192.168.1.37'")
For each objComputer in colPingedComputers
    If objComputer.StatusCode = 0 Then
        Wscript.Echo "Remote computer responded."
    Else
        Wscript.Echo "Remote computer did not respond."
   End If


Monitor Computer Health

Description
Uses cooked performance counters and the SWbemRefresher object to monitor three performance counters on a computer. Issues an alert if any of the three counters exceed the specified threshold. Requires Windows XP or Windows .NET Server.

Script Code

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 objDiskQueue = objRefresher.AddEnum _
    (objWMIService, "Win32_PerfFormattedData_PerfDisk_LogicalDisk"). _
        objectSet
Set objQueueLength = objRefresher.AddEnum _
    (objWMIService, "Win32_PerfFormattedData_PerfNet_ServerWorkQueues"). _
        objectSet
objRefresher.Refresh
intHealthStatus = 0
Do
    For each intAvailableBytes in objMemory
        If intAvailableBytes.AvailableMBytes < 4 Then
            intHealthStatus = intHealthStatus + 1
        End If
    Next
    For each intQueueLength in objDiskQueue
        If intQueueLength.CurrentDiskQueueLength > 2 Then
            intHealthStatus = intHealthStatus + 1
        End If
    Next
    For each intServerQueueLength in objQueueLength
        If intServerQueueLength.QueueLength > 4 Then
            intHealthStatus = intHealthStatus + 1
        End If
    Next
    If intHealthStatus > 0 Then
        Wscript.Echo "Unhealthy."
    Else
        Wscript.Echo "Healthy."
    End If
    intHealthStatus = 0
    Wscript.Sleep 10000
    objRefresher.Refresh
Loop


Monitor Computer Uptime

Description
Calculates the number of days since a computer was last booted. Requires Windows XP or Windows .NET Server.

Script Code

Set dtmConvertedDate = CreateObject("WbemScripting.SWbemDateTime")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colOperatingSystems = objWMIService.ExecQuery _
    ("Select * from Win32_OperatingSystem")
For Each objOS in colOperatingSystems
    dtmConvertedDate.Value = objOS.LastBootUpTime
    dtmLastBootUpTime = dtmConvertedDate.GetVarDate
    dtmSystemUptime = DateDiff("d", dtmLastBootUpTime, Now)
    Wscript.Echo dtmSystemUptime


Monitor Disk Bytes Per Second

Description
Uses cooked performance counters to monitor disk bytes per second on a computer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
set objRefresher = CreateObject("WbemScripting.SWbemRefresher")
Set colDiskDrives = objRefresher.AddEnum _
    (objWMIService, "Win32_PerfFormattedData_PerfDisk_LogicalDisk").objectSet
objRefresher.Refresh
For i = 1 to 500
    For Each objDiskDrive in colDiskDrives
    Wscript.Echo "Drive name: " & objDiskDrive.Name
    Wscript.Echo "Disk bytes per second: " & objDiskDrive.DiskBytesPerSec
    Wscript.Sleep 2000
    objRefresher.Refresh
    Next


Monitor Disk Drive Free Space

Description
Uses cooked performance counters to retrieve free disk space on a computer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDiskDrives = objWMIService.ExecQuery _
    ("Select * from win32_perfformatteddata_perfdisk_logicaldisk where Name <> '_Total'")
For each objDiskDrive in colDiskDrives
    Wscript.Echo "Drive Name: " & objDiskDrive.Name
    Wscript.Echo "Free Space: " & objDiskDrive.FreeMegabytes


Monitor Domain Controller Performance

Description

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDatabases = objWMIService.ExecQuery _
    ("Select * from Win32_PerfFormattedData_NTDS_NTDS")
For Each objADDatabase in colDatabases
    Wscript.Echo objADDatabase.DSThreadsInUse
    Wscript.Echo objADDatabase.LDAPBindTime
    Wscript.Echo objADDatabase.LDAPClientSessions


Monitor Event Logs

Description
Creates a temporary event consumer that monitors event logs for events with an event ID of 533.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate, (Security)}!\\" & strComputer & "\root\cimv2")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
    ("Select * from __instancecreationevent where TargetInstance isa 'Win32_NTLogEvent' and TargetInstance.EventCode = '533' ")
Do
    Set objLatestEvent = colMonitoredEvents.NextEvent
        strAlertToSend = objLatestEvent.TargetInstance.User _
            & " attempted to access DatabaseServer."
        Wscript.Echo strAlertToSend
Loop


Monitor FRS Replication

Description
Uses cooked performance counters to monitor File Replication Service performance on a domain controller. Requires Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFRSSet = objWMIService.ExecQuery _
 ("Select * from Win32_PerfFormattedData_FileReplicaConn_FileReplicaConn")
For Each objFRSInstance in colFRSSet
    Wscript.Echo objFRSInstance.RemoteChangeOrdersReceived
    Wscript.Echo objFRSInstance.RemoteChangeOrdersSent
    Wscript.Echo objFRSInstance.PacketsSent


Monitor Processor Use

Description
Uses cooked performance counters to monitor processor use on a computer. Triggers an alert if processor use exceeds 90 percent on 10 successive measurements (measured at 6-second intervals).

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
set objRefresher = CreateObject("WbemScripting.Swbemrefresher")
Set objProcessor = objRefresher.AddEnum _
    (objWMIService, "Win32_PerfFormattedData_PerfOS_Processor").objectSet
intThresholdViolations = 0
objRefresher.Refresh
Do
    For each intProcessorUse in objProcessor
        If intProcessorUse.PercentProcessorTime > 90 Then
            intThresholdViolations = intThresholdViolations + 1
                If intThresholdViolations = 10 Then
                    intThresholdViolations = 0
                    Wscript.Echo "Processor usage threshold exceeded."
                End If
        Else
            intThresholdViolations = 0
        End If
    Next
    Wscript.Sleep 6000
    objRefresher.Refresh
Loop


Suppress Multiple Event Notifications

Description
Issues an alert if available space on a disk drive falls below 100 megabytes. Will wait one hour before issuing the next alert.

Script Code

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


Add a Printer Connection

Description
Adds a printer connection to a network printer. Script must be run on the local computer.

Script Code

Set WshNetwork = CreateObject("WScript.Network")
WshNetwork.AddWindowsPrinterConnection "\\PrintServer1\Xerox300"
WshNetwork.SetDefaultPrinter "\\PrintServer1\Xerox300"


Change Print Job Priority

Description
Uses ADSI to change the priority of current print jobs based on the size of those print jobs.

Script Code

Set objPrinter = GetObject("WinNT://atl-dc-02/ArtDepartmentPrinter, printqueue")
For each objPrintJob in objPrinter.PrintJobs
    If objPrintJob.Size > 400000 Then
        objPrintJob.Put "Priority" , 2
        objPrintJob.SetInfo
    Else
        objPrintJob.Put "Priority" , 3
        objPrintJob.SetInfo
    End If


Change Print Job Start Time

Description
Uses ADSI to change the start time for all print jobs larger than 400K to 2 AM.

Script Code

Set objPrinter = GetObject("WinNT://atl-dc-02/ArtDepartmentPrinter,printqueue")
For each objPrintQueue in objPrinter.PrintJobs
If objPrintQueue.Size > 400000 Then
    objPrintQueue.Put "StartTime" , TimeValue("2:00:00 AM")
    objPrintQueue.SetInfo
End If


Configure Printer Availability

Description
Configures a printer so that documents can only be printed between 8 AM and 6 PM. Requires Windows XP or Windows .NET Server.

Script Code

dtmStartTime= "********080000.000000+000"
dtmEndTime= "********180000.000000+000"
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPrinters = objWMIService.ExecQuery _
    ("Select * From Win32_Printer Where DeviceID = 'ArtDepartmentPrinter' ")
For Each objPrinter in colPrinters
    objPrinter.StartTime = dtmStartTime
    objPrinter.UntilTime = dtmEndTime
    objPrinter.Put_


Configure Printer Locations

Description
Uses ADSI to configure the location attribute for all printers in a specified OU.

Script Code

Set objOU = GetObject("LDAP://OU = Finance, DC = fabrikam, DC = com")
objOU.Filter = Array("printqueue")
For Each objPrintQueue In objOU
    objPrintQueue.Put "Location" , "USA/Redmond/Finance Building"
    objPrintQueue.SetInfo


Configure Printer Priority

Description
Sets the priority for a printer to 2. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPrinters = objWMIService.ExecQuery _
    ("Select * From Win32_Printer where DeviceID = 'ArtDepartmentPrinter' ")
For Each objPrinter in colPrinters
    objPrinter.Priority = 2
    objPrinter.Put_


Delete All Printers on a Print Server

Description
Deletes all the printers from a print server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer")
For Each objPrinter in colInstalledPrinters
    objPrinter.Delete_


Delete a Printer

Description
Deletes a printer named ScriptedPrinter.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer where DeviceID = 'ScriptedPrinter'")
For Each objPrinter in colInstalledPrinters
    objPrinter.Delete_


Delete A Printer Port

Description
Deletes a TCP/IP printer port from a computer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPorts =  objWMIService.ExecQuery _
    ("Select * from Win32_TCPIPPrinterPort Where Name = 'IP_169.254.110.14'")
For Each objPort in colInstalledPorts
    objPort.Delete


Delete Print Jobs

Description
Deletes all print jobs larger than 1 megabyte. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPrintJobs =  objWMIService.ExecQuery _
    ("Select * from Win32_PrintJob Where Size > 1000000")
For Each objPrintJob in colPrintJobs
    objPrintJob.Delete_


Delete Specific Printers

Description
Deletes all HP QuietJet printers installed on a computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer Where DriverName = 'HP QuietJet'")
For Each objPrinter in colInstalledPrinters
    objPrinter.Delete_


Delete Unused Printer Ports

Description
Deletes any printer ports that have been installed on a computer but are not in use. Requires Windows XP or Windows .NET Server.

Script Code

Set objDictionary = CreateObject("Scripting.Dictionary")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer")
For Each objPrinter in colPrinters
    objDictionary.Add objPrinter.PortName, objPrinter.PortName
Next
Set colPorts = objWMIService.ExecQuery _
    ("Select * from Win32_TCPIPPrinterPort")
For Each objPort in colPorts
    If objDictionary.Exists(objPort.Name) Then
    Else
        ObjPort.Delete_
    End If


Determine Printer Port Availability

Description
Identifies all the TCP/IP printer ports on a computer, and indicates which ports are being used and which ports are available. Requires Windows XP or Windows .NET Server.

Script Code

Set objDictionary = CreateObject("Scripting.Dictionary")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer")
For Each objPrinter in colPrinters
    objDictionary.Add objPrinter.PortName, objPrinter.PortName
Next
Set colPorts = objWMIService.ExecQuery _
    ("Select * from Win32_TCPIPPrinterPort")
For Each objPort in colPorts
    If objDictionary.Exists(objPort.Name) Then
        strUsedPorts = strUsedPorts & _
            objDictionary.Item(objPort.Name) & VbCrLf
    Else
        strFreePorts = strFreePorts & objPort.Name & vbCrLf
    End If
Next
Wscript.Echo "The following ports are in use: " & VbCrLf & strUsedPorts
Wscript.Echo "The following ports are available: " & VbCrLf & strFreePorts


Enumerate All Published Printers

Description
Returns a list of all the printers published in Active Directory.

Script Code

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 printerName, serverName from " _
    & " 'LDAP://DC=fabrikam,DC=com'  where objectClass='printQueue'"
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Timeout") = 30
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCommand.Properties("Cache Results") = False
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
Do Until objRecordSet.EOF
    Wscript.Echo "Printer Name: " & objRecordSet.Fields("printerName").Value
    Wscript.Echo "Server Name: " & objRecordSet.Fields("serverName").Value
    objRecordSet.MoveNext
Loop


Enumerate Printer Capabilities

Description
Lists properties and capabilities for all the printers installed on a computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_PrinterConfiguration")
For Each objPrinter in colInstalledPrinters
    Wscript.Echo "Name: " & objPrinter.Name
    Wscript.Echo "Collate: " & objPrinter.Collate
    Wscript.Echo "Copies: " & objPrinter.Copies
    Wscript.Echo "Driver Version: " & objPrinter.DriverVersion
    Wscript.Echo "Duplex: " & objPrinter.Duplex
    Wscript.Echo "Horizontal Resolution: " & _
        objPrinter.HorizontalResolution
    If objPrinter.Orientation = 1 Then
        strOrientation =  "Portrait"
    Else
        strOrientation = "Landscape"
    End If
    Wscript.Echo "Orientation : " & strOrientation
    Wscript.Echo "Paper Length: " & objPrinter.PaperLength / 254
    Wscript.Echo "Paper Width: " & objPrinter.PaperWidth / 254
    Wscript.Echo "Print Quality: " & objPrinter.PrintQuality
    Wscript.Echo "Scale: " & objPrinter.Scale
    Wscript.Echo "Specification Version: " & _
        objPrinter.SpecificationVersion
    If objPrinter.TTOption = 1 Then
        strTTOption = "Print TrueType fonts as graphics."
    Elseif objPrinter.TTOption = 2 Then
        strTTOption = "Download TrueType fonts as soft fonts."
    Else
        strTTOption = "Substitute device fonts for TrueType fonts."
    End If
    Wscript.Echo "True Type Option: " & strTTOption
    Wscript.Echo "Vertical Resolution: " & objPrinter.VerticalResolution


Enumerate Printer Connections

Description
Enumerates all the printer connections on a computer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer")
For Each objPrinter in colInstalledPrinters
    Wscript.Echo "Name: " & objPrinter.Name
    Wscript.Echo "Location: " & objPrinter.Location
    Wscript.Echo "Default: " & objPrinter.Default


Enumerate Printer Drivers

Description
Lists all the printer drives that have been installed on a computer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_PrinterDriver")
For each objPrinter in colInstalledPrinters
    Wscript.Echo "Config File: " & objPrinter.ConfigFile
    Wscript.Echo "Data File: " & objPrinter.DataFile
    Wscript.Echo "Description: " & objPrinter.Description
    Wscript.Echo "Driver Path: " & objPrinter.DriverPath
    Wscript.Echo "File Path: " & objPrinter.FilePath
    Wscript.Echo "Help File: " & objPrinter.HelpFile
    Wscript.Echo "INF Name: " & objPrinter.InfName
    Wscript.Echo "Monitor Name: " & objPrinter.MonitorName
    Wscript.Echo "Name: " & objPrinter.Name
    Wscript.Echo "OEMUrl: " & objPrinter.OEMUrl
    Wscript.Echo "Supported Platform: " & objPrinter.SupportedPlatform
    Wscript.Echo "Version: " & objPrinter.Version


Enumerate Printer Port Properties

Description
Lists properties of all the TCP/IP printer ports installed on a computer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPorts =  objWMIService.ExecQuery _
    ("Select * from Win32_TCPIPPrinterPort")
For Each objPort in colPorts
    Wscript.Echo "Description: " & objPort.Description
    Wscript.Echo "Host Address: " & objPort.HostAddress
    Wscript.Echo "Name: " & objPort.Name
    Wscript.Echo "Port Number: " & objPort.PortNumber
    Wscript.Echo "Protocol: " & objPort.Protocol
    Wscript.Echo "SNMP Community: " & objPort.SNMPCommunity
    Wscript.Echo "SNMP Dev Index: " & objPort.SnMPDevIndex
    Wscript.Echo "SNMP Enabled: " & objPort.SNMPEnabled


Install a Printer

Description
Installs a logical network printer on a print server. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objPrinter = objWMIService.Get("Win32_Printer").SpawnInstance_
objPrinter.DriverName = "HP LaserJet 4000 Series PS"
objPrinter.PortName   = "IP_169.254.110.160"
objPrinter.DeviceID   = "ScriptedPrinter"
objPrinter.Location = "USA/Redmond/Building 37/Room 114"
objPrinter.Network = True
objPrinter.Shared = True
objPrinter.ShareName = "ScriptedPrinter"
objPrinter.Put_


Install a Printer Driver not Found in Drivers Cab

Description
Installs a hypothetical printer using a print driver not found in Drivers.cab. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
set objDriver = objWMIService.Get("Win32_PrinterDriver")
objDriver.Name = "NewPrinter Model 2900"
objDriver.SupportedPlatform = "Windows NT x86"
objDriver.Version = "3"
objDriverPath = "C:\Scripts\NewPrinter.dll"
objInfname = "C:\Scripts\NewPrinter.inf"
intResult = objDriver.AddPrinterDriver(objDriver)
Wscript.Echo intResult


Install Multiple Printers for One Print Device

Description
Installs two logical network printers (with different printer priorities) for the same physical print device. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objPrinter = objWMIService.Get("Win32_Printer").SpawnInstance_
objPrinter.DriverName = "HP LaserJet 4000 Series PS"
objPrinter.PortName   = "IP_169.254.110.160"
objPrinter.DeviceID   = "PublicPrinter"
objPrinter.Location = "USA/Redmond/Building 37/Room 114"
objPrinter.Network = True
objPrinter.Shared = True
objPrinter.ShareName = "PublicPrinter"
objPrinter.Put_

objPrinter.DriverName = "HP LaserJet 4000 Series PS"
objPrinter.PortName   = "IP_169.254.110.160"
objPrinter.DeviceID   = "PrivatePrinter"
objPrinter.Location = "USA/Redmond/Building 37/Room 114"
objPrinter.Priority = 2
objPrinter.Network = True
objPrinter.Shared = True
objPrinter.Hidden = True
objPrinter.ShareName = "PrivatePrinter"
objPrinter.Put_


Install Printer Drivers

Description
Installs the printer driver for an Apple LaserWriter 8500 printer. Requires Windows XP or Windows .NET Server.

Script Code

Set objWMIService = GetObject("winmgmts:")
Set objDriver = objWMIService.Get("Win32_PrinterDriver")
objDriver.Name = "Apple LaserWriter 8500"
objDriver.SupportedPlatform = "Windows NT x86"
objDriver.Version = "3"
errResult = objDriver.AddPrinterDriver(objDriver)


Install Printer Ports

Description
Installs a TCP/IP printer port on a computer. Requires Windows XP or Windows .NET Server.

Script Code

Set objWMIService = GetObject("winmgmts:")
Set objNewPort = objWMIService.Get _
    ("Win32_TCPIPPrinterPort").SpawnInstance_
objNewPort.Name = "IP_169.254.110.14"
objNewPort.Protocol = 1
objNewPort.HostAddress = "169.254.110.14"
objNewPort.PortNumber = "9999"
objNewPort.SNMPEnabled = False
objNewPort.Put_


Monitor Printer Status

Description
Displays current status for all printers on a computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer")
For Each objPrinter in colInstalledPrinters
    Wscript.Echo  "Name: " & objPrinter.Name
    Wscript.Echo  "Location: " & objPrinter.Location
    Select Case objPrinter.PrinterStatus
        Case 1
            strPrinterStatus = "Other"
        Case 2
            strPrinterStatus = "Unknown"
        Case 3
            strPrinterStatus = "Idle"
        Case 4
            strPrinterStatus = "Printing"
        Case 5
            strPrinterStatus = "Warmup"
    End Select
    Wscript.Echo  "Printer Status: " & strPrinterStatus
    Wscript.Echo  "Server Name: " & objPrinter.ServerName
    Wscript.Echo  "Share Name: " & objPrinter.ShareName
    Wscript.Echo


Monitor Printers with a Temporary Event Subscription

Description
Uses a temporary event consumer to issues alerts any time a printer changes status.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPrinters = objWMIService. _
    ExecNotificationQuery("Select * from __instancemodificationevent " _
        & "within 30 where TargetInstance isa 'Win32_Printer'")
i = 0
Do While i = 0
    Set objPrinter = colPrinters.NextEvent
    If objPrinter.TargetInstance.PrinterStatus <> _
        objPrinter.PreviousInstance.PrinterStatus Then
        Select Case objPrinter.TargetInstance.PrinterStatus
            Case 1 strCurrentState = "Other"
            Case 2 strCurrentState = "Unknown"
            Case 3 strCurrentState = "Idle"
            Case 4 strCurrentState = "Printing"
            Case 5 strCurrentState = "Warming Up"
        End Select
        Select Case objPrinter.PreviousInstance.PrinterStatus
            Case 1 strPreviousState = "Other"
            Case 2 strPreviousState = "Unknown"
            Case 3 strPreviousState = "Idle"
            Case 4 strPreviousState = "Printing"
            Case 5 strPreviousState = "Warming Up"
        End Select
        Wscript.Echo objPrinter.TargetInstance.Name _
            &  " is " & strCurrentState _
                & ". The printer previously was " & strPreviousState & "."
    End If
Loop


Monitor Print Job Status

Description
Returns the job ID, user name, and total pages for each print job on a computer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPrintJobs =  objWMIService.ExecQuery _
    ("Select * from Win32_PrintJob")
Wscript.Echo "Print Queue, Job ID, Owner, Total Pages"
For Each objPrintJob in colPrintJobs
    strPrinter = Split(objPrintJob.Name,",",-1,1)
    Wscript.Echo strPrinter(0) & ", " & _
        objPrintJob.JobID & ", " &  objPrintJob.Owner & ", " _
            & objPrintJob.TotalPages


Monitor Print Queues

Description
Uses cooked performance counters to return the number of jobs currently in each print queue on a computer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPrintQueues =  objWMIService.ExecQuery _
    ("Select * from Win32_PerfFormattedData_Spooler_PrintQueue Where Name <> '_Total'")
For Each objPrintQueue in colPrintQueues
    Wscript.Echo "Name: " & objPrintQueue.Name
    Wscript.Echo "Current jobs: " & objPrintQueue.Jobs


Monitor Print Queue Times

Description
Identifies any print jobs that have been in the print queue for more than 15 minutes. Requires Windows XP or Windows .NET Server.

Script Code

Const USE_LOCAL_TIME = True
Set DateTime = CreateObject("WbemScripting.SWbemDateTime")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_PrintJob")
Wscript.Echo "Print Queue, Job ID, TimeSubmitted, Total Pages"
For Each objPrinter in colInstalledPrinters
    DateTime.Value = objPrinter.TimeSubmitted
    dtmActualTime = DateTime.GetVarDate(USE_LOCAL_TIME)
    TimeinQueue = DateDiff("n", actualTime, Now)
    If TimeinQueue > 15 Then
        strPrinterName = Split(objPrinter.Name,",",-1,1)
        Wscript.Echo strPrinterName(0) & ", " _
            & objPrinter.JobID & ", " & dtmActualTime & ", " & _
                objPrinter.TotalPages
    End If


Monitor the Print Service

Description
Returns the status of the Spooler service (running, stopped, paused, etc.).

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colRunningServices =  objWMIService.ExecQuery _
    ("Select * from Win32_Service Where Name = 'Spooler'")
For Each objService in colRunningServices
    Wscript.Echo objService.DisplayName  & VbTab & objService.State


Notify Users of a Purged Print Queue

Description
Uses Msg.exe to send a network alert to any users who had documents in a print queue about to be purged. After sending the alert, the script purges the print queue. Requires Windows XP or Windows .NET Server.

Script Code

Set WshShell = Wscript.CreateObject("Wscript.Shell")
Set objDictionary = CreateObject("Scripting.Dictionary")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrintJobs =  objWMIService.ExecQuery _
    ("Select * from Win32_PrintJob")
For Each objPrintJob in colInstalledPrintJobs
    strPrinterName = Split(objPrintJob.Name,",",-1,1)
    If objDictionary.Exists(objPrintJob.Notify) Then
    Else
        objDictionary.Add objPrintJob.Notify, strPrinterName(0)
    End If
Next
arrKeys = objDictionary.Keys
arrItems = objDictionary.Items
For i = 0 to objDictionary.Count - 1
    Message = "The documents you were printing on printer "
    Message = Message & arrItems(i)
    Message = Message & " had to be deleted from the print queue. "
    Message = Message & "You will need to reprint these documents."
    CommandString = "%comspec% /c msg " & arrKeys(i) & " " & Chr(34) _
        & Message & Chr(34)
    WshShell.Run CommandString, 0, True
Next
Set colInstalledPrinters = objWMIService.ExecQuery _
    ("Select * from Win32_Printer")
For Each objPrinter in colInstalledPrinters
    objPrinter.CancelAllJobs()


Pause a Printer

Description
Pauses a printer named ArtDepartmentPrinter. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer Where Name = 'ArtDepartmentPrinter'")
For Each objPrinter in colInstalledPrinters
    objPrinter.Pause()


Pause Printers with Empty Print Queues

Description
Pauses any printers that have no pending print jobs. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer")
For Each objPrinter in colInstalledPrinters
    Set colPrintJobs = objWMIService.ExecQuery _
        ("Select * from Win32_PerfFormattedData_Spooler_PrintQueue " _
            & "Where Name = '" & objPrinter.Name & "'")
    For Each objPrintQueue in colPrintJobs
        If objPrintQueue.Jobs = 0 and objPrintQueue.Name <> "_Total" Then
            objPrinter.Pause()
        End If
    Next


Pause Print Jobs

Description
Pauses all the print jobs on a computer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPrintJobs =  objWMIService.ExecQuery _
    ("Select * from Win32_PrintJob")
For Each objPrintJob in colPrintJobs
    objPrintJob.Pause


Purge a Print Queue

Description
Deletes all the print jobs for a printer named HP QuietJet.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer Where Name = 'HP QuietJet'")
For Each objPrinter in colInstalledPrinters
    objPrinter.CancelAllJobs()


Receive Notification When a Printer Stops

Description
Checks the status for each printer on a computer, and issues an alert if any of these printers have stopped.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer Where PrinterStatus = '1' " _
        & "or PrinterStatus = '2'")
If colInstalledPrinters.Count = 0 Then
    Wscript.Echo "All printers are functioning correctly."
Else
    For Each objPrinter in colInstalledPrinters
        Wscript.Echo "Printer " & objprinter.Name & " is not responding."
End If


Remove a Printer Connection

Description
Removes a printer connection to a network printer. Script must be run on the local computer.

Script Code

Set WshNetwork = WScript.CreateObject("WScript.Network")
WshNetwork.RemovePrinterConnection "\\PrintServer\xerox3006"


Rename a Printer

Description
Renames both a printer and its printer share name. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer Where DeviceID = 'HP LaserJet 4Si M'")
For Each objPrinter in colPrinters
    objPrinter.RenamePrinter("ArtDepartmentPrinter")
Next
Set colPrinters = objWMIService.ExecQuery _
    ("Select * From Win32_Printer Where DeviceID = 'ArtDepartmentPrinter' ")
For Each objPrinter in colPrinters
    objPrinter.ShareName = "ArtDepartmentPrinter"
    objPrinter.Put_


Report Print Queue Statistics

Description
Returns total number of jobs, total number of pages, and largest job for all print queues on a computer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPrintJobs =  objWMIService.ExecQuery _
    ("Select * from Win32_PrintJob")
For Each objPrintJob in colPrintJobs
    intTotalJobs = intTotalJobs + 1
    intTotalPages = intTotalPages + objPrintJob.TotalPages
    If objPrintJob.TotalPages > intMaxPrintJob Then
        intMaxPrintJob = objPrintJob.TotalPages
    End If
Next
Wscript.Echo "Total print jobs in queue: " & intTotalJobs
Wscript.Echo "Total pages in queue: " & intTotalPages
Wscript.Echo "Largest print job in queue: " & intMaxPrintJob


Resume All Paused Printers

Description
Resumes all the paused printers on a print server. Requires Windows XP or Windows .NET Server.

Script Code

Const PRINTER_IS_PAUSED = 8
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer where ExtendedPrinterStatus = 8")
For Each objPrinter in colInstalledPrinters
    ObjPrinter.Resume()


Resume a Paused Printer

Description
Resumes a paused printer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer Where Name = 'ArtDepartmentPrinter'")
For Each objPrinter in colInstalledPrinters
    objPrinter.Resume()


Resume Print Jobs

Description
Resumes all the print jobs on a computer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPrintJobs =  objWMIService.ExecQuery _
    ("Select * from Win32_PrintJob")
For Each objPrintJob in colPrintJobs
    objPrintJob.Resume


Retrieve Print Queue Statistics

Description
Uses cooked performance counters to retrieve data such as total number of jobs printed and total number of printing errors for each print queue on a computer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPrintQueues =  objWMIService.ExecQuery _
    ("Select * from Win32_PerfFormattedData_Spooler_PrintQueue Where Name <> '_Total'")
For Each objPrintQueue in colPrintQueues
    Wscript.Echo "Name: " & objPrintQueue.Name
    Wscript.Echo "Jobs: " & objPrintQueue.Jobs
    Wscript.Echo "Current jobs spooling: " & objPrintQueue.JobsSpooling
    Wscript.Echo "Maximum jobs spooling: " & objPrintQueue.MaxJobsSpooling
    Wscript.Echo "Total jobs printed: " & objPrintQueue.TotalJobsPrinted
    Wscript.Echo "NamJob errors: " & objPrintQueue.JobErrors
    Wscript.Echo "Not ready errors: " & objPrintQueue.NotReadyErrors
    Wscript.Echo "Out of paper errors: " & objPrintQueue.OutOfPaperErrors


Search for Specific Printers

Description
Searches Active Directory for all printers with a priority of 2.

Script Code

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 printerName, serverName from " _
    & "'LDAP://DC=fabrikam,DC=com'  where objectClass='printQueue' and " _
        & " Priority = 2 "
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Timeout") = 30
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCommand.Properties("Cache Results") = False
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
Do Until objRecordSet.EOF
    Wscript.Echo "Printer Name: " & objRecordSet.Fields("printerName").Value
    Wscript.Echo "Server Name: " & objRecordSet.Fields("serverName").Value
    objRecordSet.MoveNext
Loop


Set the Default Printer

Description
Sets the default printer on a computer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer Where Name = 'ScriptedPrinter'")
For Each objPrinter in colInstalledPrinters
    objPrinter.SetDefaultPrinter()


Set the Default Printer Based on Queue Length

Description
Examines all the print queues on a computer, and sets the default printer to the queue with the fewest documents.

Script Code

intSmallestQueue = 1000
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPrintQueues =  objWMIService.ExecQuery _
    ("Select * from Win32_PerfFormattedData_Spooler_PrintQueue " _
        & "Where Name <> '_Total'")
For Each objPrintQueue in colPrintQueues
    intCurrentQueue = objPrintQueue.Jobs + objPrintQueue.JobsSpooling
    If intCurrentQueue <= intSmallestQueue Then
        strNewDefault = objPrintQueue.Name
        intSmallestQueue = intCurrentQueue
    End If
Next
Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer Where Name = '" & strNewDefault & "'")
For Each objPrinter in colInstalledPrinters
    objPrinter.SetDefaultPrinter()


Transfer Print Jobs to a Different Print Queue

Description
Changes the TCP/IP printer port for a logical printer, which has the net effect of transferring existing print jobs to the new printer port, and thus to a different printer. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objPrinter = objWMIService.Get _
    ("Win32_Printer.DeviceID='ArtDepartmentPrinter'")
objPrinter.PortName = "IP_192.168.1.10"
objPrinter.Put_


Update Printer Locations

Description
Uses ADSI to update the location attribute for all printers in a specified OU.

Script Code

Set objOU = GetObject("LDAP://OU=Finance, DC=fabrikam, DC=com")
objOU.Filter = Array("printqueue")
For Each objPrintQueue In objOU
    strNewLocation = "Redmond/" & objPrintQueue.Location
    objPrintQueue.Put "Location" , strNewLocation
    objPrintQueue.SetInfo


Change the Priority Of a Running Process

Description
Changes the priority of a running instance of Notepad.exe from Normal to Above Normal. Requires Windows XP or Windows .NET Server.

Script Code

Const ABOVE_NORMAL = 32768
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery _
    ("Select * from Win32_Process Where Name = 'Notepad.exe'")
For Each objProcess in colProcesses
    objProcess.SetPriority(ABOVE_NORMAL)


Create a Higher Priority Process

Description
Starts Notepad.exe with an Above Normal priority.

Script Code

Const ABOVE_NORMAL = 32768
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objStartup = objWMIService.Get("Win32_ProcessStartup")
Set objConfig = objStartup.SpawnInstance_
objConfig.PriorityClass = ABOVE_NORMAL
Set objProcess = GetObject("winmgmts:root\cimv2:Win32_Process")
objProcess.Create "Notepad.exe", Null, objConfig, intProcessID


Create a Process in a Hidden Window

Description
Starts Notepad.exe on the local computer, but in a hidden window.

Script Code

Const HIDDEN_WINDOW = 12
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objStartup = objWMIService.Get("Win32_ProcessStartup")
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = HIDDEN_WINDOW
Set objProcess = GetObject("winmgmts:root\cimv2:Win32_Process")
errReturn = objProcess.Create("Notepad.exe", null, objConfig, intProcessID)


Create a Process on a Remote Computer

Description
Starts Notepad.exe on a remote computer. On Windows XP and .NET Server, Notepad will run in a hidden window.

Script Code

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

Error = objWMIService.Create("notepad.exe", null, null, intProcessID)
If Error = 0 Then
    Wscript.Echo "Notepad was started with a process ID of " _
         & intProcessID & "."
Else
    Wscript.Echo "Notepad could not be started due to error " & _
        Error & "."
End If


Determine Process Ownership

Description
Reports the account name under which each process on a computer is running.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery _
    ("Select * from Win32_Process")
For Each objProcess in colProcessList
    colProperties = objProcess.GetOwner(strNameOfUser,strUserDomain)
    Wscript.Echo "Process " & objProcess.Name & " is owned by " _
        & strUserDomain & "\" & strNameOfUser & "."


Monitor Process Availability

Description
Identifies whether or not a hypothetical process Database.exe is running.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery _
    ("Select * from Win32_Process Where Name = 'Database.exe'")
If colProcesses.Count = 0 Then
    Wscript.Echo "Database.exe is not running."
Else
    Wscript.Echo "Database.exe is running."
End If


Monitor Process Creation

Description
Temporary event consumer that issues an alert each time a new process is created.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colMonitoredProcesses = objWMIService. _
    ExecNotificationQuery("select * from __instancecreationevent " _
        & " within 1 where TargetInstance isa 'Win32_Process'")
i = 0
Do While i = 0
    Set objLatestProcess = colMonitoredProcesses.NextEvent
    Wscript.Echo objLatestProcess.TargetInstance.Name
Loop


Monitor Process Deletion

Description
Temporary event consumer that issues an alert each time a process terminates.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colMonitoredProcesses = objWMIService. _
    ExecNotificationQuery("select * from __instancedeletionevent " _
            & "within 1 where TargetInstance isa 'Win32_Process'")
i = 0
Do While i = 0
    Set objLatestProcess = colMonitoredProcesses.NextEvent
    Wscript.Echo objLatestProcess.TargetInstance.Name
Loop


Monitor Processor Use by Process

Description
Reports processor use time, in seconds, for each process running on a computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery _
    ("Select * from Win32_process")
For Each objProcess in colProcesses
    sngProcessTime = ( CSng(objProcess.KernelModeTime) + _
            CSng(objProcess.UserModeTime)) / 10000000
    Wscript.echo objProcess.name & VbTab & sngProcessTime


Monitor Process Performance

Description
Reports statistics such as thread count and working set size for all processes running on a computer.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery _
    ("Select * from Win32_Process")
For Each objProcess in colProcessList
    Wscript.Echo "Process: " & objProcess.Name
    Wscript.Echo "Process ID: " & objProcess.ProcessID
    Wscript.Echo "Thread Count: " & objProcess.ThreadCount
    Wscript.Echo "Page File Size: " & objProcess.PageFileUsage
    Wscript.Echo "Page Faults: " & objProcess.PageFaults
    Wscript.Echo "Working Set Size: " & objProcess.WorkingSetSize


Monitor Threads

Description
Returns a list of threads and thread states for each process running on a computer.

Script Code

Set objDictionary = CreateObject("Scripting.Dictionary")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery _
    ("Select * from Win32_Process")
For each objProcess in colProcesses
    objDictionary.Add objProcess.ProcessID, objProcess.Name
Next
Set colThreads = objWMIService.ExecQuery _
    ("Select * from Win32_Thread")
For each objThread in colThreads
    intProcessID = CInt(objThread.ProcessHandle)
    strProcessName = objDictionary.Item(intProcessID)
    Wscript.Echo strProcessName & VbTab & objThread.ProcessHandle & _
        VbTab & objThread.Handle & VbTab & objThread.ThreadState


Prevent a Process from Running

Description
Temporary event consumer that terminates any new instances of Notepad.exe as soon as those new instances are created.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colMonitoredProcesses = objWMIService. _
    ExecNotificationQuery("select * from __instancecreationevent " _
        & " within 1 where TargetInstance isa 'Win32_Process'")
i = 0
Do While i = 0
    Set objLatestProcess = colMonitoredProcesses.NextEvent
    If objLatestProcess.TargetInstance.Name = "notepad.exe" Then
    objLatestProcess.TargetInstance.Terminate
    End If
Loop


Terminate a Process

Description
Terminates any running instances of Notepad.exe.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery _
    ("Select * from Win32_Process Where Name = 'Notepad.exe'")
For Each objProcess in colProcessList
    objProcess.Terminate()


Check Registry Key Access Rights

Description
Uses WMI to check access rights for the logged on user to HKLM\SYSTEM\CurrentControlSet.

Script Code

const KEY_QUERY_VALUE = &H0001
const KEY_SET_VALUE = &H0002
const KEY_CREATE_SUB_KEY = &H0004
const DELETE = &H00010000

const HKEY_LOCAL_MACHINE = &H80000002

strComputer = "."
Set StdOut = WScript.StdOut

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

strKeyPath = "SYSTEM\CurrentControlSet"

oReg.CheckAccess HKEY_LOCAL_MACHINE, strKeyPath, KEY_QUERY_VALUE, bHasAccessRight
If bHasAccessRight = True Then
    StdOut.WriteLine "Have Query Value Access Rights on Key"
Else
    StdOut.WriteLine "Do Not Have Query Value Access Rights on Key"
End If

oReg.CheckAccess HKEY_LOCAL_MACHINE, strKeyPath, KEY_SET_VALUE, bHasAccessRight
If bHasAccessRight = True Then
    StdOut.WriteLine "Have Set Value Access Rights on Key"
Else
    StdOut.WriteLine "Do Not Have Set Value Access Rights on Key"
End If

oReg.CheckAccess HKEY_LOCAL_MACHINE, strKeyPath, KEY_CREATE_SUB_KEY, bHasAccessRight
If bHasAccessRight = True Then
    StdOut.WriteLine "Have Create SubKey Access Rights on Key"
Else
    StdOut.WriteLine "Do Not Have Create SubKey Access Rights on Key"
End If

oReg.CheckAccess HKEY_LOCAL_MACHINE, strKeyPath, DELETE, bHasAccessRight
If bHasAccessRight = True Then
    StdOut.WriteLine "Have Delete Access Rights on Key"
Else
    StdOut.WriteLine "Do Not Have Delete Access Rights on Key"
End If


Create a Registry Key

Description
Uses WMI to create a registry key HKLM\SOFTWARE\System Admin Scripting Guide.

Script Code

const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set StdOut = WScript.StdOut

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

strKeyPath = "SOFTWARE\System Admin Scripting Guide"
oReg.CreateKey HKEY_LOCAL_MACHINE,strKeyPath


Create Expanded String Values

Description
Uses WMI to create an expanded string value under HKLM\SOFTWARE\System Admin Scripting Guide.

Script Code

const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."

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

strKeyPath = "SOFTWARE\System Admin Scripting Guide"
strValueName = "Expanded String Value Name"
strValue = "%PATHEXT%"

oReg.SetExpandedStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue


Create a MultiString Value

Description
Uses WMI to create a string a multi-string value under HKLM\SOFTWARE\System Admin Scripting Guide.

Script Code

const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."

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

strKeyPath = "SOFTWARE\System Admin Scripting Guide"
strValueName = "Multi String Value Name"
arrStringValues = Array("first string", "second string",_
 "third string", "fourth string")

oReg.SetMultiStringValue HKEY_LOCAL_MACHINE,strKeyPath,_
strValueName,arrStringValues


Create String and DWORD Values

Description
Uses WMI to create string and DWORD values under HKLM\SOFTWARE\System Admin Scripting Guide.

Script Code

const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set StdOut = WScript.StdOut

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

strKeyPath = "SOFTWARE\System Admin Scripting Guide"
strValueName = "String Value Name"
strValue = "string value"
oReg.SetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue

strValueName = "DWORD Value Name"
dwValue = 82
oReg.SetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,dwValue


Delete a Registry Key

Description
Uses WMI to delete the registry key HKLM\SOFTWARE\System Admin Scripting Guide.

Script Code

const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."

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

strKeyPath = "SOFTWARE\System Admin Scripting Guide"

oReg.DeleteKey HKEY_LOCAL_MACHINE, strKeyPath


Delete Registry Values

Description
Uses WMI to delete all the registry values under HKLM\SOFTWARE\System Admin Scripting Guide.

Script Code

const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."

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

strKeyPath = "SOFTWARE\System Admin Scripting Guide"
strDWORDValueName = "DWORD Value Name"
strExpandedStringValueName = "Expanded String Value Name"
strMultiStringValueName = "Multi String Value Name"
strStringValueName = "String Value Name"

oReg.DeleteValue HKEY_LOCAL_MACHINE,strKeyPath,strDWORDValueName
oReg.DeleteValue HKEY_LOCAL_MACHINE,strKeyPath,strExpandedStringValueName
oReg.DeleteValue HKEY_LOCAL_MACHINE,strKeyPath,strMultiStringValueName
oReg.DeleteValue HKEY_LOCAL_MACHINE,strKeyPath,strStringValueName


Enumerate Registry Values and Types

Description
Uses WMI to list all the registry values and their types under HKLM\SYSTEM\CurrentControlSet\Control\Lsa.

Script Code

const HKEY_LOCAL_MACHINE = &H80000002
const REG_SZ = 1
const REG_EXPAND_SZ = 2
const REG_BINARY = 3
const REG_DWORD = 4
const REG_MULTI_SZ = 7

strComputer = "."
Set StdOut = WScript.StdOut

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

strKeyPath = "SYSTEM\CurrentControlSet\Control\Lsa"

oReg.EnumValues HKEY_LOCAL_MACHINE, strKeyPath,_
 arrValueNames, arrValueTypes

For i=0 To UBound(arrValueNames)
    StdOut.WriteLine "Value Name: " & arrValueNames(i)

    Select Case arrValueTypes(i)
        Case REG_SZ
            StdOut.WriteLine "Data Type: String"
            StdOut.WriteBlankLines(1)
        Case REG_EXPAND_SZ
            StdOut.WriteLine "Data Type: Expanded String"
            StdOut.WriteBlankLines(1)
        Case REG_BINARY
            StdOut.WriteLine "Data Type: Binary"
            StdOut.WriteBlankLines(1)
        Case REG_DWORD
            StdOut.WriteLine "Data Type: DWORD"
            StdOut.WriteBlankLines(1)
        Case REG_MULTI_SZ
            StdOut.WriteLine "Data Type: Multi String"
            StdOut.WriteBlankLines(1)
    End Select


Enumerate Subkeys

Description
Uses WMI to enumerate all the registry subkeys under HKLM\SYSTEM\CurrentControlSet\Services.

Script Code

const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set StdOut = WScript.StdOut

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

strKeyPath = "SYSTEM\CurrentControlSet\Services"
oReg.EnumKey HKEY_LOCAL_MACHINE, strKeyPath, arrSubKeys

For Each subkey In arrSubKeys
    StdOut.WriteLine subkey


List Registry Files

Description
Uses WMI to list all the registry file and locations under HKLM\System\CurrentControlSet\Control\Hivelist.

Script Code

const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set StdOut = WScript.StdOut

Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" &_
strComputer & "\root\default:StdRegProv")
strKeyPath = "System\CurrentControlSet\Control\hivelist"
oReg.EnumValues HKEY_LOCAL_MACHINE, strKeyPath,_
 arrValueNames, arrValueTypes

For i=0 To UBound(arrValueNames)
    StdOut.WriteLine "File Name: " & arrValueNames(i) & " -- "
    oReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,_
    arrValueNames(i),strValue
    StdOut.WriteLine "Location: " & strValue
    StdOut.WriteBlankLines(1)


Monitor Registry Entry Level Events

Description
Temporary event consumer that monitors the registry for any changes to HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\CSDVersion.

Script Code

Set wmiServices = GetObject("winmgmts:root/default")
Set wmiSink = WScript.CreateObject("WbemScripting.SWbemSink", "SINK_")

wmiServices.ExecNotificationQueryAsync wmiSink, _
    "SELECT * FROM RegistryValueChangeEvent WHERE Hive='HKEY_LOCAL_MACHINE' AND " & _
    "KeyPath='SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion' AND ValueName='CSDVersion'"

WScript.Echo "Listening for Registry Change Events..." & vbCrLf

While(1)
    WScript.Sleep 1000
Wend

Sub SINK_OnObjectReady(wmiObject, wmiAsyncContext)
    WScript.Echo "Received Registry Change Event" & vbCrLf & _
                 "------------------------------" & vbCrLf & _
                 wmiObject.GetObjectText_()
End Sub


Monitor Registry Subkey Events

Description
Temporary event consumer that monitors the registry for any changes to HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion.

Script Code

Set wmiServices = GetObject("winmgmts:root/default")
Set wmiSink = WScript.CreateObject("WbemScripting.SWbemSink", "SINK_")

wmiServices.ExecNotificationQueryAsync wmiSink, _
    "SELECT * FROM RegistryKeyChangeEvent WHERE Hive='HKEY_LOCAL_MACHINE' AND " & _
    "KeyPath='SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'"

WScript.Echo "Listening for Registry Change Events..." & vbCrLf

While(1)
    WScript.Sleep 1000
Wend

Sub SINK_OnObjectReady(wmiObject, wmiAsyncContext)
    WScript.Echo "Received Registry Change Event" & vbCrLf & _
                 "------------------------------" & vbCrLf & _
                 wmiObject.GetObjectText_()
End Sub


Monitor Registry Subtree Events

Description
Temporary event consumer that monitors the registry for any changes to HKLM.

Script Code

Set wmiServices = GetObject("winmgmts:root/default")
Set wmiSink = WScript.CreateObject("WbemScripting.SWbemSink", "SINK_")

wmiServices.ExecNotificationQueryAsync wmiSink, _
    "SELECT * FROM RegistryTreeChangeEvent WHERE Hive='HKEY_LOCAL_MACHINE' AND RootPath=''"

WScript.Echo "Listening for Registry Change Events..." & vbCrLf

While(1)
    WScript.Sleep 1000
Wend

Sub SINK_OnObjectReady(wmiObject, wmiAsyncContext)
    WScript.Echo "Received Registry Change Event" & vbCrLf & _
                 "------------------------------" & vbCrLf & _
                 wmiObject.GetObjectText_()
End Sub


Read a Binary Registry Value

Description
Uses WMI to read a binary registry value.

Script Code

const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set StdOut = WScript.StdOut

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

strKeyPath = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"
strValueName = "LicenseInfo"
oReg.GetBinaryValue HKEY_LOCAL_MACHINE,strKeyPath,_
strValueName,strValue

For i = lBound(strValue) to uBound(strValue)
    StdOut.WriteLine  strValue(i)


Read a MultiString Value

Description
Uses WMI to read a multi-string registry value.

Script Code

const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set StdOut = WScript.StdOut

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

strKeyPath = "SYSTEM\CurrentControlSet\Services\Eventlog\System"
strValueName = "Sources"
oReg.GetMultiStringValue HKEY_LOCAL_MACHINE,strKeyPath,_
strValueName,arrValues

For Each strValue In arrValues
    StdOut.WriteLine  strValue


Read an Expanded String Value

Description
Uses WMI to read an expanded string registry value.

Script Code

const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set StdOut = WScript.StdOut

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

strKeyPath = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon"
strValueName = "UIHost"
oReg.GetExpandedStringValue HKEY_LOCAL_MACHINE,strKeyPath,_
strValueName,strValue

StdOut.WriteLine  "The Windows logon UI host is: " & strValue


Read String and DWORD Values

Description
Uses WMI to read a string and a DWORD registry value.

Script Code

const HKEY_CURRENT_USER = &H80000001
const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set StdOut = WScript.StdOut

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

strKeyPath = "Console"
strValueName = "HistoryBufferSize"
oReg.GetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,dwValue
StdOut.WriteLine "Current History Buffer Size: " & dwValue

strKeyPath = "SOFTWARE\Microsoft\Windows Script Host\Settings"
strValueName = "TrustPolicy"
oReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue
StdOut.WriteLine "Current WSH Trust Policy Value: " & strValue


Programmatically Verify a Script Signature

Description
Verifies that an individual script has been digitally signed.

Script Code

blnShowGUI = False
set objSigner = WScript.CreateObject("Scripting.Signer")
blnShowGUI = False
blnIsSigned = objSigner.VerifyFile("C:\Scripts\CreateUser.vbs", blnShowGUI)
If blnIsSigned then
    WScript.Echo "Script has been signed."
Else
   WScript.Echo " Script has not been signed."
End If


Sign All Scripts in a Folder

Description
Uses the Scripting Runtime Signer object to digitally sign all the scripts in a folder. Requires a valid digital certificate.

Script Code

set objSigner = WScript.CreateObject("Scripting.Signer")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("c:\scripts")
Set colListOfFiles = objFolder.Files
For each objFile in colListOfFiles
    objSigner.SignFile objFile.Path, "IT Department"


Sign a Script Programmatically

Description
Uses the Scripting Runtime Signer object to digitally sign a script. Requires a valid digital certificate.

Script Code

set objSigner = WScript.CreateObject("Scripting.Signer")
objSigner.SignFile "C:\Scripts\CreateUsers.vbs", "IT Department"


Verify Signatures for All Scripts in a Folder

Description
Verifies that all the scripts in the C:\Scripts folder have been digitally signed.

Script Code

blnShowGUI = False
set objSigner = WScript.CreateObject("Scripting.Signer")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\Scripts\")
Set colListOfFiles = objFolder.Files
For each objFile in colListOfFiles
If Right(objFile.Name, 3) = "vbs" Then
    blnIsSigned = objSigner.VerifyFile(objFile.Path, blnShowGUI)
    If blnIsSigned then
        WScript.Echo objFile.Name & " has been signed."
        Else
            WScript.Echo objFile.Name & " has not been signed."
    End If
End If


Change a Service Account Password

Description
Changes the service account password for any services running under the hypothetical service account Netsvc.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery _
    ("Select * from Win32_Service")
For Each objservice in colServiceList
    If objService.Startname = ".\netsvc" Then
        errReturn = objService.Change( , , , , , , , "password")
    End If


Configure Service Error Control Codes

Description
Configures all auto-start services to issue an alert if the service fails during startup.

Script Code

Const NORMAL_ERROR_CONTROL = 2
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery _
    ("Select * from Win32_Service where ErrorControl = 'Ignore'")
For Each objService in colServiceList
    errReturn = objService.Change( , , , NORMAL_ERROR_CONTROL)


Configure Service Start Options

Description
Disables all services configured as manual start. Among other things, this prevents Power Users from being able to start these services.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery _
    ("Select * from Win32_Service where StartMode = 'Manual'")
For Each objService in colServiceList
    errReturnCode = objService.Change( , , , , "Disabled")


Determine Services Running in All Processes

Description
Returns a list of processes and all the services currently running in each process.

Script Code

set objIdDictionary = CreateObject("Scripting.Dictionary")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service Where State <> 'Stopped'")
For Each objService in colServices
    If objIdDictionary.Exists(objService.ProcessID) Then
    Else
        objIdDictionary.Add objService.ProcessID, objService.ProcessID
    End If
Next
colProcessIDs = objIdDictionary.Items
For i = 0 to objIdDictionary.Count - 1
    Set colServices = objWMIService.ExecQuery _
        ("Select * from Win32_Service Where ProcessID = '" & _
            colProcessIDs(i) & "'")
    Wscript.Echo "Process ID: " & colProcessIDs(i)
    For Each objService in colServices
        Wscript.Echo VbTab & objService.DisplayName
    Next


Determine Services Running in a Process

Description
Returns a list of services running in the Services.exe process.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service")
For Each objService in colListOfServices
    If objService.PathName = "C:\WINDOWS\system32\services.exe" Then
        Wscript.Echo objService.DisplayName
    End If


Determine Services that can be Paused

Description
Returns a list of services that can be paused.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service Where AcceptPause = True")
For Each objService in colServices
    Wscript.Echo objService.DisplayName


Determine Services that can be Stopped

Description
Returns a list of services that can be stopped.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service Where AcceptStop = True")
For Each objService in colServices
    Wscript.Echo objService.DisplayName


Enumerate Antecedent Services for a Single Service

Description
Enumerates all the services that must be running before the SMTP service can be started.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery("Associators of " _
 & "{Win32_service.Name='SMTPSVC'} Where " _
    & "AssocClass=Win32_DependentService " & "Role=Dependent")
For Each objService in colServiceList
    Wscript.Echo objService.DisplayName


Enumerate Dependent Services for All Services

Description
Enumerates dependent services for all the services installed on a computer.

Script Code

Const ForAppending = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLogFile = _
     objFSO.OpenTextFile("c:\scripts\service_dependencies.csv", _
         ForAppending, True)
objLogFile.Write("Service Dependencies")
objLogFile.Writeline
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service")

For Each objService in colListofServices
    objServiceRegistryName = objService.Name
    objServiceDisplayName = objService.DisplayName

Set colServiceList = objWMIService.ExecQuery("Associators of " _
   & "{Win32_Service.Name='" & objServiceRegistryName & "'} Where AssocClass=Win32_DependentService Role=Antecedent" )

 If colServiceList.Count = 0 then
        objLogFile.Write(objServiceDisplayName) & ", None"
        objLogFile.Writeline
    Else
        For Each objDependentService in colServiceList
            objLogFile.Write(objServiceDisplayName) & ","
            objLogFile.Write(objDependentService.DisplayName)
        Next
        objLogFile.WriteLine
    End If
objLogFile.Close


Enumerate Dependent Services for a Single Service

Description
Enumerates all the services that cannot start until the Rasman service has started.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery("Associators of " _
   & "{Win32_Service.Name='rasman'} Where " _
        & "AssocClass=Win32_DependentService " & "Role=Antecedent" )
For Each objService in colServiceList
    Wscript.Echo objService.DisplayName


Enumerate Inactive Services

Description
Returns a list of all the services installed on a computer that are currently stopped.

Script Code

strComputer = "."

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

Set colStoppedServices = objWMIService.ExecQuery _
  ("SELECT DisplayName,State FROM Win32_Service WHERE State <> 'Running'")

For Each objService in colStoppedServices
    Wscript.Echo objService.DisplayName  & " = " & objService.State


Install a Service

Description
Installs a hypothetical service Db.exe.

Script Code

Const OWN_PROCESS = 16
Const NOT_INTERACTIVE = False
Const NORMAL_ERROR_CONTROL = 2
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objService = objWMIService.Get("Win32_BaseService")
errReturn = objService.Create("DbService" ,"Personnel Database" , "c:\windows\system32\db.exe", OWN_PROCESS, NORMAL_ERROR_CONTROL, "Manual", NOT_INTERACTIVE, "NT AUTHORITY\LocalService", ""  )
Wscript.Echo errReturn


Monitor Changes in Service Status

Description
Temporary event consumer that issues an alert any time a service changes status (for example, an active service that is paused or stopped).

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServices = objWMIService. _
    ExecNotificationQuery("Select * from __instancemodificationevent " _
        & "within 30 where TargetInstance isa 'Win32_Service'")
i = 0
Do While i = 0
    Set objService = colServices.NextEvent
    If objService.TargetInstance.State <> _
        objService.PreviousInstance.State Then
        Wscript.Echo objService.TargetInstance.Name _
            &  " is " & objService.TargetInstance.State _
                & ". The service previously was " & objService.PreviousInstance.State & "."
    End If
Loop


Monitor Service Performance

Description
Uses formatted performance counters to retrieve performance data for the DHCP Server service. Requires Windows XP or Windows .NET Server.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
set objRefresher = CreateObject("WbemScripting.SWbemRefresher")
Set colDHCPServer = objRefresher.AddEnum _
    (objWMIService, "win32_PerfFormattedData_DHCPServer_DHCPServer"). _
          ObjectSet
objRefresher.Refresh
For i = 1 to 60
    For Each objDHCPServer in colDHCPServer
        Wscript.Echo "Acknowledgements per second: " & _
            objDHCPServer.AcksPerSec
        Wscript.Echo "Declines per second: " & _
            objDHCPServer.DeclinesPerSec
        Wscript.Echo "Discovers per second: " & _
            objDHCPServer.DiscoversPerSec
        Wscript.Echo "Informs per second: " & objDHCPServer.InformsPerSec
        Wscript.Echo "Offers per second: " & objDHCPServer.OffersPerSec
        Wscript.Echo "Releases per second: " & _
            objDHCPServer.ReleasesPerSec
        Wscript.Echo "Requests per second: " & _
            objDHCPServer.RequestsPerSec
    Next
    Wscript.Sleep 10000
    objRefresher.Refresh


Pause Services Running Under a Specific Account

Description
Pauses all services running under the hypothetical service account Netsvc.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service")
For each objService in colServices
    If objService.StartName = ".\netsvc" Then
        errReturnCode = objService.PauseService()
    End If


Remove a Service

Description
Removes a hypothetical service named DbService.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service Where Name = 'DbService'")
For Each objService in colListOfServices
    objService.StopService()
    objService.Delete()


Resume AutoStart Services that are Paused

Description
Restarts any auto-start services that have been paused.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery _
 ("Select * from Win32_Service Where State = 'Paused' and StartMode = 'Auto'")
For Each objService in colListOfServices
    objService.ResumeService()


Retrieve Service Properties

Description
Retrieves a complete list of services and their associated properties. Information is saved to a text file: C:\Scripts\Service_List.cs.

Script Code

Const ForAppending = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLogFile = objFSO.OpenTextFile("c:\scripts\service_list.csv", _
    ForAppending, True)
objLogFile.Write _
    ("System Name,Service Name,Service Type,Service State, Exit " _
        & "Code,Process ID,Can Be Paused,Can Be Stopped,Caption," _
        & "Description,Can Interact with Desktop,Display Name,Error " _
        & "Control, Executable Path Name,Service Started," _
        & "Start Mode,Account Name ")
objLogFile.Writeline
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery _
        ("Select * from Win32_Service")
For Each objService in colListOfServices
    objLogFile.Write(objService.SystemName) & ","
    objLogFile.Write(objService.Name) & ","
    objLogFile.Write(objService.ServiceType) & ","
    objLogFile.Write(objService.State) & ","
    objLogFile.Write(objService.ExitCode) & ","
    objLogFile.Write(objService.ProcessID) & ","
    objLogFile.Write(objService.AcceptPause) & ","
    objLogFile.Write(objService.AcceptStop) & ","
    objLogFile.Write(objService.Caption) & ","
    objLogFile.Write(objService.Description) & ","
    objLogFile.Write(objService.DesktopInteract) & ","
    objLogFile.Write(objService.DisplayName) & ","
    objLogFile.Write(objService.ErrorControl) & ","
    objLogFile.Write(objService.PathName) & ","
    objLogFile.Write(objService.Started) & ","
    objLogFile.Write(objService.StartMode) & ","
    objLogFile.Write(objService.StartName) & ","
    objLogFile.writeline
objLogFile.Close


Retrieve Service Status

Description
Returns a list of all the services installed on a computer, and indicates their current status (typically, running or not running).

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colRunningServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service")
For Each objService in colRunningServices
    Wscript.Echo objService.DisplayName  & VbTab & objService.State


Retrieve Service Status Changes from Event Logs

Description
Retrieves events from the System event log that have an event ID of 7036. These events are recorded any time a service changes status. Requires Windows XP or Windows .NET Server.

Script Code

Set dtmConvertedDate = CreateObject("WbemScripting.SWbemDateTime")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceEvents = objWMIService.ExecQuery _
    ("Select * from Win32_NTLogEvent Where Logfile = 'System' and " _
        & "EventCode = '7036'")
For Each strEvent in colServiceEvents
    dtmConvertedDate.Value = strEvent.TimeWritten
    Wscript.Echo dtmConvertedDate.GetVarDate
    Wscript.Echo strEvent.Message


Start a Service and Its Dependents

Description
Starts the NetDDE service and all its dependent services.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery _
    ("Select * from Win32_Service where Name='NetDDE'")
For each objService in colServiceList
    errReturn = objService.StartService()
Next
Wscript.Sleep 20000
Set colServiceList = objWMIService.ExecQuery("Associators of " _
   & "{Win32_Service.Name='NetDDE'} Where " _
        & "AssocClass=Win32_DependentService " & "Role=Dependent" )
For each objService in colServiceList
    objService.StartService()


Start AutoStart Services that have Stopped

Description
Restarts any auto-start services that have been stopped.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery _
 ("Select * from Win32_Service Where State = 'Stopped' and StartMode = " _
     & "'Auto'")
For Each objService in colListOfServices
    objService.StartService()


Stop a Service and Its Dependents

Description
Stops the NetDDE service and all its dependent services.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery("Associators of " _
   & "{Win32_Service.Name='NetDDE'} Where " _
        & "AssocClass=Win32_DependentService " & "Role=Antecedent" )
For each objService in colServiceList
    objService.StopService()
Next
Wscript.Sleep 20000
Set colServiceList = objWMIService.ExecQuery _
        ("Select * from Win32_Service where Name='NetDDE'")
For each objService in colServiceList
    errReturn = objService.StopService()


Stop Services Running Under a Specific Account

Description
Stops all services running under the hypothetical service account Netsvc.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServices = objWMIService.ExecQuery _
    ("Select * from win32_Service")
For each objService in colServices
    If objService.StartName = ".\netsvc" Then
        errReturnCode = objService.StopService()
    End If


Switch Service Accounts to Local Service

Description
Changes the service account to LocalService for any services running under the hypothetical service account Netsvc.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service")
For each objService in colServices
    If objService.StartName = ".\netsvc" Then
        errServiceChange = objService.Change _
        ( , , , , , , "NT AUTHORITY\LocalService" , "")
    End If


Delete All Scheduled Tasks

Description
Deletes all the scheduled tasks on a computer. Note: WMI can only delete scheduled tasks created with the Win32_ScheduledJob class or the At.exe utility. It cannot delete tasks created using the Task Scheduler.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colScheduledTasks = objWMIService.ExecQuery _
    ("Select * from Win32_ScheduledJob")
For Each objTask in colScheduledTasks
    intJobID = objTask.JobID
    Set objInstance = objWMIService.Get("Win32_ScheduledJob.JobID=" & intJobID)
    objInstance.Delete


Delete a Scheduled Task

Description
Deletes the scheduled task with the JobID of 1.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objInstance = objWMIService.Get("Win32_ScheduledJob.JobID=1")
err = objInstance.Delete
Wscript.Echo err


Enumerate Scheduled Tasks

Description
Enumerates all the scheduled tasks on a computer. Note: WMI can only enumerate scheduled tasks created with the Win32_ScheduledJob class or the At.exe utility. It cannot enumerate tasks created using the Task Scheduler.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colScheduledJobs = objWMIService.ExecQuery _
    ("Select * from Win32_ScheduledJob")
For Each objJob in colScheduledJobs
    Wscript.Echo "Caption: " & objJob.Caption
    Wscript.Echo "Command: " & objJob.Command
    Wscript.Echo "Days Of Month: " & objJob.DaysOfMonth
    Wscript.Echo "Days Of Week: " & objJob.DaysOfWeek
    Wscript.Echo "Description: " & objJob.Description
    Wscript.Echo "Elapsed Time: " & objJob.ElapsedTime
    Wscript.Echo "Install Date: " & objJob.InstallDate
    Wscript.Echo "Interact with Desktop: " & objJob.InteractWithDesktop
    Wscript.Echo "Job ID: " & objJob.JobID
    Wscript.Echo "Job Status: " & objJob.JobStatus
    Wscript.Echo "Name: " & objJob.Name
    Wscript.Echo "Notify: " & objJob.Notify
    Wscript.Echo "Owner: " & objJob.Owner
    Wscript.Echo "Priority: " & objJob.Priority
    Wscript.Echo "Run Repeatedly: " & objJob.RunRepeatedly
    Wscript.Echo "Start Time: " & objJob.StartTime
    Wscript.Echo "Status: " & objJob.Status
    Wscript.Echo "Time Submitted: " & objJob.TimeSubmitted
    Wscript.Echo "Until Time: " & objJob.UntilTime


Schedule a Task

Description
Schedules Notepad to run at 12:30 PM every Monday, Wednesday, and Friday.

Script Code

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objNewJob = objWMIService.Get("Win32_ScheduledJob")
errJobCreated = objNewJob.Create _
    ("Notepad.exe", "********123000.000000-420", _
        True , 1 OR 4 OR 16, , , JobID)
Wscript.Echo errJobCreated


Append a MultiValued Attribute

Description
Adds an additional URL to a user account. Demonstrates how to append a new value to a multi-valued attribute.

Script Code

Const ADS_PROPERTY_APPEND = 3

Set objUser = GetObject _
   ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")

objUser.PutEx ADS_PROPERTY_APPEND, _
  "url", Array("http://www.fabrikam.com/policy")

objUser.SetInfo


Append a Phone Number

Description
Appends an additional home phone number for a user.

Script Code

Const ADS_PROPERTY_APPEND = 3

Set objUser = GetObject _
   ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")

objUser.PutEx ADS_PROPERTY_APPEND, _
  "otherHomePhone", Array("(425) 555-1113")

objUser.SetInfo


Change User Password

Description
Changes the password for a user. Requires you to know the user's previous password.

Script Code

Set objUser = GetObject _
("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.ChangePassword "i5A2sj*!", "jl3R86df"


Change User Account Attributes

Description
Configures user account attributes found on the General Properties page of the user account object in Active Directory users and Computers.

Script Code

Const ADS_PROPERTY_UPDATE = 2
Set objUser = GetObject _
   ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")

objUser.Put "givenName", "Ken"
objUser.Put "initials", "E."
objUser.Put "sn", "Myer"
objUser.Put "displayName", "Myer, Ken"
objUser.Put "physicalDeliveryOfficeName", "Room 4358"
objUser.Put "telephoneNumber", "(425) 555-1211"
objUser.Put "mail", "myerken@fabrikam.com"
objUser.Put "wWWHomePage", "http://www.fabrikam.com"

objUser.PutEx ADS_PROPERTY_UPDATE, _
    "description", Array("Management staff")
objUser.PutEx ADS_PROPERTY_UPDATE, _
    "otherTelephone", Array("(800) 555-1212", "(425) 555-1213")
objUser.PutEx ADS_PROPERTY_UPDATE, _
     "url", Array("http://www.fabrikam.com/management")

objUser.SetInfo


Clear Attributes

Description
Clears selected attributes for a user account.

Script Code

Const ADS_PROPERTY_CLEAR = 1

Set objUser = GetObject _
   ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")

objUser.PutEx ADS_PROPERTY_CLEAR, "initials", 0
objUser.PutEx ADS_PROPERTY_CLEAR, "otherTelephone", 0

objUser.SetInfo


Clear Telephone Attributes

Description
Clears selected telephone-related attributes for a user account.

Script Code

Const ADS_PROPERTY_CLEAR = 1

Set objUser = GetObject _
   ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")

objUser.PutEx ADS_PROPERTY_CLEAR, "info", 0
objUser.PutEx ADS_PROPERTY_CLEAR, "otherPager", 0

objUser.SetInfo


Clear User Account Address Attributes

Description
Clears selected address-related attributes for a user account.

Script Code

Const ADS_PROPERTY_CLEAR = 1
Set objUser = GetObject _
   ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")

objUser.PutEx ADS_PROPERTY_CLEAR, "streetAddress", 0
objUser.PutEx ADS_PROPERTY_CLEAR, "c", 0

objUser.SetInfo


Configure User Profile Properties

Description
Configures user profile settings for a user account.

Script Code

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")

objUser.Put "profilePath", "\\sea-dc-01\Profiles\myerken"
objUser.Put "scriptPath", "logon.bat"
objUser.Put "homeDirectory", "\\sea-dc-01\HomeFolders\myerken"
objUser.Put "homeDrive", "H"

objUser.SetInfo


Configure User Telephone Properties

Description
Configures telephone numbers and telephone-related attributes for a user account.

Script Code

Const ADS_PROPERTY_UPDATE = 2
Set objUser = GetObject _
   ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")

objUser.Put "homePhone", "(425) 555-1111"
objUser.Put "pager", "(425) 555-2222"
objUser.Put "mobile", "(425) 555-3333"
objUser.Put "facsimileTelephoneNumber", "(425) 555-4444"
objUser.Put "ipPhone", "5555"
objUser.Put "info", "Please do not call this user account" & _
  " at home unless there is a work-related emergency. Call" & _
  " this user's mobile phone before calling the pager number"

objUser.PutEx ADS_PROPERTY_UPDATE, _
    "otherHomePhone", Array("(425) 555-1112")
objUser.PutEx ADS_PROPERTY_UPDATE, _
    "otherPager", Array("(425) 555-2223")
objUser.PutEx ADS_PROPERTY_UPDATE, _
    "otherMobile", Array("(425) 555-3334", "(425) 555-3335")
objUser.PutEx ADS_PROPERTY_UPDATE, _
    "otherFacsimileTelephoneNumber", Array("(425) 555-4445")
objUser.PutEx ADS_PROPERTY_UPDATE, _
    "otherIpPhone", Array("6666")

objUser.SetInfo


Create User Account

Description
Creates a user account in Active Directory. This script only creates the account, it does not enable it.

Script Code

Set objOU = GetObject("LDAP://OU=management,dc=fabrikam,dc=com")
Set objUser = objOU.Create("User", "cn=MyerKen")
objUser.Put "sAMAccountName", "myerken"
objUser.SetInfo


Delete a Phone Number

Description
Deletes a phone number from a user account with multiple mobile phone numbers.

Script Code

Const ADS_PROPERTY_DELETE = 4

Set objUser = GetObject _
   ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")

objUser.PutEx ADS_PROPERTY_DELETE, _
  "otherMobile", Array("(425) 555-3334")

objUser.SetInfo


Delete Attributes

Description
Deletes selected attributes from a user account. Demonstrates how to delete single-valued attributes as well as how to delete a single entry from a multi-valued attribute.

Script Code

Const ADS_PROPERTY_DELETE = 4

Set objUser = GetObject _
   ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")

objUser.PutEx ADS_PROPERTY_DELETE, _
  "otherTelephone", Array("(425) 555-1213")
objUser.PutEx ADS_PROPERTY_DELETE, _
  "initials", Array("E.")

objUser.SetInfo


Delete A User Account

Description
Deletes a user account from Active Directory.

Script Code

Set objOU = GetObject("LDAP://ou=management,dc=fabrikam,dc=com")
objOU.Delete "User", "cn=myerken"


Determine Logon Hours

Description
Retrieves the allowed logon hours for a user.

Script Code

Dim arrLogonHoursBytes(20)
Dim arrLogonHoursBits(167)
arrDayOfWeek = Array _
  ("Sun", "Mon", "Tue", "Wed", _
   "Thu", "Fri", "Sat")

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.GetInfoEx Array("logonHours"), 0
arrLogonHours = objUser.Get("logonHours")

For i = 1 To LenB(arrLogonHours)
     arrLogonHoursBytes(i-1) = AscB(MidB(arrLogonHours, i, 1))
Next

intCounter = 0
intLoopCounter = 0
WScript.Echo "Day  Byte 1   Byte 2   Byte 3"
For Each LogonHourByte In arrLogonHoursBytes
  arrLogonHourBits = GetLogonHourBits(LogonHourByte)

   If intCounter = 0 Then
    WScript.STDOUT.Write arrDayOfWeek(intLoopCounter) & Space(2)
    intLoopCounter = intLoopCounter + 1
  End If

    For Each LogonHourBit In arrLogonHourBits
        WScript.STDOUT.Write LogonHourBit
        intCounter = 1 + intCounter

        If intCounter = 8 or intCounter = 16 Then
          WScript.STDOUT.Write Space(1)
        End If

        If intCounter = 24 Then
          WScript.echo VbCr
          intCounter = 0
        End If
    Next
Next

Function GetLogonHourBits(x)
    Dim arrBits(7)
    For i = 7 to 0 Step -1
        If x And 2^i Then
            arrBits(i) = 1
        Else
            arrBits(i) = 0
        End If
    Next
    GetLogonHourBits = arrBits
End Function


Determine User Account Status

Description
Identifies whether a user account is enabled or disabled.

Script Code

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")

If objUser.AccountDisabled = FALSE Then
      WScript.echo "The account is enabled."
Else
      WScript.echo "The account is disabled."
End If


Determine When an Account Expires

Description
Returns the expiration date for a user account.

Script Code

On Error Resume Next
Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")

dtmAccountExpiration = objUser.AccountExpirationDate

If err.number = -2147467259 Or _
 dtmAccountExpiration = "1/1/1970" Then
  WScript.echo "No account expiration specified"
Else
  WScript.echo "Account expiration:" & _
    objUser.AccountExpirationDate
End If


Determine When a Password Expires

Description
Determines the date when a user password will expire.

Script Code

Const SEC_IN_DAY = 86400
Const ADS_UF_DONT_EXPIRE_PASSWD = &h10000

Set objUserLDAP = GetObject _
  ("LDAP://CN=myerken,OU=management,DC=fabrikam,DC=com")
intCurrentValue = objUserLDAP.Get("userAccountControl")

If intCurrentValue and ADS_UF_DONT_EXPIRE_PASSWD Then
  wscript.echo "The password does not expire."
Else
  dtmValue = objUserLDAP.PasswordLastChanged
  Wscript.echo "The password was last changed on " & _
  DateValue(dtmValue) & " at " & TimeValue(dtmValue) & VbCrLf & _
  "The difference between when the password was last set" & VbCrLf & _
  "and today is " & int(now - dtmValue) & " days"
  intTimeInterval = int(now - dtmValue)

  Set objDomainNT = GetObject("WinNT://fabrikam")
  intMaxPwdAge = objDomainNT.Get("MaxPasswordAge")
  If intMaxPwdAge < 0 Then
    WScript.Echo "The Maximum Password Age is set to 0 in the " & _
      "domain. Therefore, the password does not expire."
  Else
    intMaxPwdAge = (intMaxPwdAge/SEC_IN_DAY)
    Wscript.echo "The maximum password age is " & intMaxPwdAge & " days"
    If intTimeInterval >= intMaxPwdAge Then
      Wscript.echo "The password has expired."
    Else
      Wscript.echo "The password will expire on " & _
      DateValue(dtmValue + intMaxPwdAge) & " (" & _
      int((dtmValue + intMaxPwdAge) - now) & " days from today" & ")."
    End If
  End If
End If


Determine When a Password was Last Set

Description
Identifies the last time a user password was set.

Script Code

Set objUser = GetObject _
("LDAP://CN=myerken,OU=management,DC=Fabrikam,DC=com")
dtmValue = objUser.PasswordLastChanged
WScript.echo "pwdLastSet is: " & dtmValue


Disable a Password Flag

Description
Disables the option allowing a password to be stored using reversible encrypted text.

Script Code

Const ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = &H80

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
intUAC = objUser.Get("userAccountControl")

If intUAC AND _
  ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED Then
    objUser.Put "userAccountControl", intUAC XOR _
      ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED
    objUser.SetInfo
End If


Disable a User Account

Description
Disables a user account.

Script Code

Const ADS_UF_ACCOUNTDISABLE = 2

Set objUser = GetObject _
("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
intUAC = objUser.Get("userAccountControl")

objUser.Put "userAccountControl", intUAC OR ADS_UF_ACCOUNTDISABLE
objUser.SetInfo


Disable the User Cannot Change Password Option

Description
Disables the User Cannot Change Password option, allowing the user to change their password.

Script Code

Const ADS_ACETYPE_ACCESS_DENIED_OBJECT = &H6
Const CHANGE_PASSWORD_GUID  = _
  "{ab721a53-1e2f-11d0-9819-00aa0040529b}"

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
Set objSD   = objUser.Get("nTSecurityDescriptor")
Set objDACL = objSD.DiscretionaryAcl
arrTrustees = Array("nt authority\self", "everyone")

For Each strTrustee In arrTrustees
  For Each ace In objDACL
    If(LCase(ace.Trustee) = strTrustee) Then
      If((ace.AceType = ADS_ACETYPE_ACCESS_DENIED_OBJECT) And _
        (LCase(ace.ObjectType) = CHANGE_PASSWORD_GUID)) Then
        objDACL.RemoveAce ace
      End If
    End If
  Next
Next

objUser.Put "nTSecurityDescriptor", objSD
objUser.SetInfo


Display Domain Password Attributes

Description
Displays password policy settings for the domain.

Script Code

Const MIN_IN_DAY = 1440, SEC_IN_MIN = 60

Set objDomain = GetObject("WinNT://fabrikam")
Set objAdS = GetObject("LDAP://dc=fabrikam,dc=com")

intMaxPwdAgeSeconds = objDomain.Get("MaxPasswordAge")
intMinPwdAgeSeconds = objDomain.Get("MinPasswordAge")
intLockOutObservationWindowSeconds = objDomain.Get("LockoutObservationInterval")
intLockoutDurationSeconds = objDomain.Get("AutoUnlockInterval")
intMinPwdLength = objAds.Get("minPwdLength")

intPwdHistoryLength = objAds.Get("pwdHistoryLength")
intPwdProperties = objAds.Get("pwdProperties")
intLockoutThreshold = objAds.Get("lockoutThreshold")
intMaxPwdAgeDays = _
  ((intMaxPwdAgeSeconds/SEC_IN_MIN)/MIN_IN_DAY) & " days"
intMinPwdAgeDays = _
  ((intMinPwdAgeSeconds/SEC_IN_MIN)/MIN_IN_DAY) & " days"
intLockOutObservationWindowMinutes = _
  (intLockOutObservationWindowSeconds/SEC_IN_MIN) & " minutes"

If intLockoutDurationSeconds <> -1 Then
  intLockoutDurationMinutes = _
(intLockOutDurationSeconds/SEC_IN_MIN) & " minutes"
Else
  intLockoutDurationMinutes = _
    "Administrator must manually unlock locked accounts"
End If

WScript.echo "maxPwdAge = " & intMaxPwdAgeDays
WScript.echo "minPwdAge = " & intMinPwdAgeDays
WScript.echo "minPwdLength = " & intMinPwdLength
WScript.echo "pwdHistoryLength = " & intPwdHistoryLength
WScript.echo "pwdProperties = " & intPwdProperties
WScript.echo "lockOutThreshold = " & intLockoutThreshold
WScript.echo "lockOutObservationWindow = " & intLockOutObservationWindowMinutes
WScript.echo "lockOutDuration = " & intLockoutDurationMinutes


Display Password Property Attributes

Description
Displays password settings for the domain.

Script Code

Set objHash = CreateObject("Scripting.Dictionary")

objHash.Add "DOMAIN_PASSWORD_COMPLEX", &h1
objHash.Add "DOMAIN_PASSWORD_NO_ANON_CHANGE", &h2
objHash.Add "DOMAIN_PASSWORD_NO_CLEAR_CHANGE", &h4
objHash.Add "DOMAIN_LOCKOUT_ADMINS", &h8
objHash.Add "DOMAIN_PASSWORD_STORE_CLEARTEXT", &h16
objHash.Add "DOMAIN_REFUSE_PASSWORD_CHANGE", &h32

Set objDomain = GetObject("LDAP://dc=fabrikam,dc=com")

intPwdProperties = objDomain.Get("PwdProperties")
WScript.echo "pwdProperties = " & intPwdProperties

For Each Key In objHash.Keys
  If objHash(Key) And intPwdProperties Then
    WScript.Echo Key & " is enabled"
  Else
    WScript.Echo Key & " is disabled"
  End If


Display User Account Password Attributes

Description
Displays password-related attributes for an individual user account.

Script Code

Const ADS_UF_PASSWORD_EXPIRED = &h800000
Const ADS_ACETYPE_ACCESS_DENIED_OBJECT = &H6
Const CHANGE_PASSWORD_GUID = "{ab721a53-1e2f-11d0-9819-00aa0040529b}"

Set objHash = CreateObject("Scripting.Dictionary")
objHash.Add "ADS_UF_PASSWD_NOTREQD", &h00020
objHash.Add "ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED", &h0080
objHash.Add "ADS_UF_DONT_EXPIRE_PASSWD", &h10000

Set objUser = GetObject _
    ("LDAP://CN=MyerKen,OU=management,DC=Fabrikam,DC=com")
intUserAccountControl = objUser.Get("userAccountControl")

Set objUserNT = GetObject("WinNT://fabrikam/myerken")
intUserFlags = objUserNT.Get("userFlags")

If ADS_UF_PASSWORD_EXPIRED And intUserFlags Then
  blnExpiredFlag = True
  Wscript.Echo "ADS_UF_PASSWORD_EXPIRED is enabled"
Else
  Wscript.Echo "ADS_UF_PASSWORD_EXPIRED is disabled"
End If

For Each Key In objHash.Keys
  If objHash(Key) And intUserAccountControl Then
    WScript.Echo Key & " is enabled"
  Else
    WScript.Echo Key & " is disabled"
  End If
Next

Set objSD = objUser.Get("nTSecurityDescriptor")
Set objDACL = objSD.DiscretionaryAcl
For Each Ace In objDACL
  If ((Ace.AceType = ADS_ACETYPE_ACCESS_DENIED_OBJECT) And _
      (LCase(Ace.ObjectType) = CHANGE_PASSWORD_GUID)) Then
    blnACEPresent = True
  End If
Next
If blnACEPresent Then
  Wscript.Echo "ADS_UF_PASSWD_CANT_CHANGE is enabled"
Else
  Wscript.Echo "ADS_UF_PASSWD_CANT_CHANGE is disabled"
End If

If blnExpiredFlag = True Then
  Wscript.echo "pwdLastSet is null"
Else
  Wscript.echo "pwdLastSet is " & objUser.PasswordLastChanged
End If


Enable a User Account

Description
Enables a user account.

Script Code

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.AccountDisabled = FALSE
objUser.SetInfo


Enable a userAccountControl Flag

Description
Uses the userAccountControl to require a user to logon using a smart card.

Script Code

Const ADS_UF_SMARTCARD_REQUIRED = &h40000

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
intUAC = objUser.Get("userAccountControl")

If (intUAC AND ADS_UF_SMARTCARD_REQUIRED) = 0 Then
    objUser.Put "userAccountControl", intUAC XOR ADS_UF_SMARTCARD_REQUIRED
    objUser.SetInfo
End If


Ensure that an Account will not Expire

Description
Configures a user account so that it wil not expire. This is done by setting the expiration date to 1/1/1970.

Script Code

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.AccountExpirationDate = "01/01/1970"
objUser.SetInfo


Modify the User Profile Path

Description
Configures the user profile path for a user.

Script Code

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")

objUser.GetInfoEx Array("profilePath"), 0
strCurrentProfilePath = objUser.Get("profilePath")

intStringLen = Len(strCurrentProfilePath)
intStringRemains = intStringLen - 11
strRemains = Mid(strCurrentProfilePath, 12, intStringRemains)
strNewProfilePath = "\\fabrikam" & strRemains

objUser.Put "profilePath", strNewProfilePath
objUser.SetInfo


Prevent a Password Change

Description
Enables the User Cannot Change Password option, which prevents the user from changing their password.

Script Code

Const ADS_ACETYPE_ACCESS_DENIED_OBJECT = &H6
Const ADS_ACEFLAG_OBJECT_TYPE_PRESENT = &H1
Const CHANGE_PASSWORD_GUID = "{ab721a53-1e2f-11d0-9819-00aa0040529b}"
Const ADS_RIGHT_DS_CONTROL_ACCESS = &H100

Set objUser = GetObject _
    ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
Set objSD = objUser.Get("ntSecurityDescriptor")
Set objDACL = objSD.DiscretionaryAcl
arrTrustees = array("nt authority\self", "EVERYONE")

For Each strTrustee in arrTrustees
  Set objACE = CreateObject("AccessControlEntry")
      objACE.Trustee = strTrustee
  objACE.AceFlags = 0
  objACE.AceType = ADS_ACETYPE_ACCESS_DENIED_OBJECT
  objACE.Flags = ADS_ACEFLAG_OBJECT_TYPE_PRESENT
  objACE.ObjectType = CHANGE_PASSWORD_GUID
  objACE.AccessMask = ADS_RIGHT_DS_CONTROL_ACCESS
  objDACL.AddAce objACE
Next

objSD.DiscretionaryAcl = objDACL
objUser.Put "nTSecurityDescriptor", objSD
objUser. SetInfo


Require a Password Change

Description
Forces a user to change their password the next time they logon.

Script Code

Set objUser = GetObject _
    ("LDAP://CN=myerken,OU=management,DC=Fabrikam,DC=com")
objUser.Put "pwdLastSet", 0
objUser.SetInfo


Retrieve Account Properties

Description
Retrieves user account attributes found on the Account page of the user account object in Active Directory users and Computers.

Script Code

On Error Resume Next
Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.GetInfo

strUserPrincipalName = objUser.Get("userPrincipalName")
strSAMAccountName = objUser.Get("sAMAccountName")
strUserWorkstations = objUser.Get("userWorkstations")

Set objDomain = GetObject("LDAP://dc=fabrikam,dc=com")
objDomain.GetInfoEx Array("dc"), 0
strDC = objDomain.Get("dc")

WScript.echo "userPrincipalName: " & strUserPrincipalName
WScript.echo "sAMAccountName: " & strSAMAccountName
WScript.echo "UserWorkstations: " & strUserWorkstations
WScript.echo "dc: " & strDC


Retrieve Organization Information

Description
Retrieves user account attributes found on the Organization page of the user account object in Active Directory users and Computers.

Script Code

On Error Resume Next
Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.GetInfo

strTitle = objUser.Get("title")
strDepartment = objUser.Get("department")
strCompany = objUser.Get("company")
strManager = objUser.Get("manager")

strDirectReports = _
  objUser.GetEx("directReports")

WScript.echo "title: " & strTitle
WScript.echo "department: " & strDepartment
WScript.echo "company: " & strCompany
WScript.echo "manager: " & strManager

For Each strValue in strDirectReports
  WScript.echo "directReports: " & strValue


Retrieve the Password Change Attribute

Description
Identifies whether or not a user is allowed to change their password.

Script Code

Const ADS_ACETYPE_ACCESS_DENIED_OBJECT = &H6
Const CHANGE_PASSWORD_GUID  = _
 "{ab721a53-1e2f-11d0-9819-00aa0040529b}"
Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
Set objSD = objUser.Get("nTSecurityDescriptor")
Set objDACL = objSD.DiscretionaryAcl
For Each Ace In objDACL
  If ((Ace.AceType = ADS_ACETYPE_ACCESS_DENIED_OBJECT) And _
      (LCase(Ace.ObjectType) = CHANGE_PASSWORD_GUID)) Then
    blnEnabled = True
  End If
Next
If blnEnabled Then
  WScript.Echo "ADS_UF_PASSWD_CANT_CHANGE is enabled"
Else
  WScript.Echo "ADS_UF_PASSWD_CANT_CHANGE is disabled"
End If


Retrieve User Account Address Attributes

Description
Retrieves user account attributes found on the Address page of the user account object in Active Directory users and Computers.

Script Code

On Error Resume Next

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.GetInfo

strStreetAddress = objUser.Get("streetAddress")
strPostOfficeBox = objUser.Get("postOfficeBox")
strLocalityName = objUser.Get("l")
strStreetName = objUser.Get("st")
strPostalCode = objUser.Get("postalCode")
strCountryName = objUser.Get("c")

WScript.echo "streetAddress: " & strStreetAddress
WScript.echo "postOfficeBox: " & strPostOfficeBox
WScript.echo "l: " & strLocalityName
WScript.echo "st: " & strStreetName
WScript.echo "postalCode: " & strPostalCode
WScript.echo "c: " & strCountryName


Retrieve userAccountControl Attributes

Description
Uses the userAccountControl to identify whether or not a user account is locked, and whether or not that account is enabled.

Script Code

Set objHash = CreateObject("Scripting.Dictionary")

objHash.Add "ADS_UF_SMARTCARD_REQUIRED", &h40000
objHash.Add "ADS_UF_TRUSTED_FOR_DELEGATION", &h80000
objHash.Add "ADS_UF_NOT_DELEGATED", &h100000
objHash.Add "ADS_UF_USE_DES_KEY_ONLY", &h200000
objHash.Add "ADS_UF_DONT_REQUIRE_PREAUTH", &h400000

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.GetInfoEx Array("userAccountControl"), 0

intUAC = objUser.Get("userAccountControl")

If objUser.IsAccountLocked = True Then
  WScript.echo "ADS_UF_LOCKOUT is enabled"
Else
  WScript.echo "ADS_UF_LOCKOUT is disabled"
End If

For Each Key In objHash.Keys
  If objHash(Key) And intUAC Then
    WScript.Echo Key & " is enabled"
  Else
    WScript.Echo Key & " is disabled"
  End If


Retrieve User Account Properties

Description
Retrieves user account attributes found on the General Properties page of the user account object in Active Directory users and Computers.

Script Code

On Error Resume Next
Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.GetInfo

strGivenName = objUser.Get("givenName")
strInitials = objUser.Get("initials")
strSn = objUser.Get("sn")
strDisplayName = objUser.Get("displayName")
strPhysicalDeliveryOfficeName = _
  objUser.Get("physicalDeliveryOfficeName")
strTelephoneNumber = objUser.Get("telephoneNumber")
strMail = objUser.Get("mail")
strWwwHomePage = objUser.Get("wWWHomePage")

strDescription = objUser.GetEx("description")
strOtherTelephone = objUser.GetEx("otherTelephone")
strUrl = objUser.GetEx("url")

WScript.echo "givenName: " & strGivenName
WScript.echo "initials: " & strInitials
WScript.echo "sn: " & strSn
WScript.echo "displayName: " & strDisplayName
WScript.echo "physicalDeliveryOfficeName: " & _
 strPhysicalDeliveryOfficeName
WScript.echo "telephoneNumber: " & strTelephoneNumber
WScript.echo "mail: " & strMail
WScript.echo "wWWHomePage: " & strWwwHomePage

For Each strValue in strDescription
  WScript.echo "description: " & strValue
Next
For Each strValue in strOtherTelephone
  WScript.echo "otherTelephone: " & strValue
Next
For Each strValue in strUrl
  WScript.echo "url: " & strValue


Retrieve User Profile Properties

Description
Retrieves user account attributes found on the Profile page of the user account object in Active Directory users and Computers.

Script Code

On Error Resume Next
Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.GetInfo

strProfilePath = objUser.Get("profilePath")
strScriptPath = objUser.Get("scriptPath")
strHomeDirectory = objUser.Get("homeDirectory")
strHomeDrive = objUser.Get("homeDrive")

WScript.echo "profilePath: " & strProfilePath
WScript.echo "scriptPath: " & strScriptPath
WScript.echo "homeDirectory: " & strHomeDirectory
WScript.echo "homeDrive: " & strHomeDrive


Retrieve User Telephone Properties

Description
Retrieves user account attributes found on the Telephones page of the user account object in Active Directory users and Computers.

Script Code

On Error Resume Next
Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.GetInfo

strHomePhone = objUser.Get("homePhone")
strPager = objUser.Get("pager")
strMobile = objUser.Get("mobile")
strIpPhone = objUser.Get("ipPhone")
strInfo = objUser.Get("info")
strFacsimileTelephoneNumber = _
  objUser.Get("facsimileTelephoneNumber")

strOtherHomePhone = objUser.GetEx("otherHomePhone")
strOtherPager = objUser.GetEx("otherPager")
strOtherMobile = objUser.GetEx("otherMobile")
strOtherIpPhone = objUser.GetEx("otherIpPhone")
strOtherFacsimileTelephoneNumber = _
    objUser.GetEx("otherFacsimileTelephoneNumber")

WScript.echo "homePhone: " & strHomePhone
WScript.echo "pager: " & strPager
WScript.echo "mobile: " & strMobile
WScript.echo "ipPhone: " & strIpPhone
WScript.echo "info: " & strInfo
WScript.echo "facsimileTelephoneNumber: " & _
 strFacsimileTelephoneNumber

For Each strValue in strOtherHomePhone
  WScript.echo "otherHomePhone: " & strValue
Next
For Each strValue in strOtherPager
  WScript.echo "otherPager: " & strValue
Next
For Each strValue in strOtherMobile
  WScript.echo "otherMobile: " & strValue
Next
For Each strValue in strOtherIpPhone
  WScript.echo "otherIpPhone: " & strValue
Next
For Each strValue in strOtherFacsimileTelephoneNumber
  WScript.echo "otherFacsimileTelephoneNumber: " & strValue


Set an Account Expiration Date

Description
Configures a user account to expire on 3/30/2003.

Script Code

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.AccountExpirationDate = "03/30/2003"
objUser.SetInfo


Set User Password

Description
Configures a new password for a user.

Script Code

Set objUser = GetObject _
 ("LDAP://cn=MyerKen,ou=management,dc=fabrikam,dc=com")
objUser.SetPassword "i5A2sj*!"


Unlock a User Account

Description
Unlocks a locked user account.

Script Code

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.IsAccountLocked = False
objUser.SetInfo


Use Flags to Determine Account Status

Description
Uses the userAccountControl to determine whether a user account is enabled or disabled.

Script Code

Const ADS_UF_ACCOUNTDISABLE = 2

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
intUAC = objUser.Get("userAccountControl")

If intUAC AND ADS_UF_ACCOUNTDISABLE Then
  Wscript.echo "The account is disabled"
Else
  Wscript.echo "The account is enabled"
End If


Use Flags to Enable a User Account

Description
Uses the userAccountControl to enable a user account.

Script Code

Const ADS_UF_ACCOUNTDISABLE = 2

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
intUAC = objUser.Get("userAccountControl")

If intUAC AND ADS_UF_ACCOUNTDISABLE Then
  objUser.Put "userAccountControl", intUAC XOR ADS_UF_ACCOUNTDISABLE
  objUser.SetInfo
End If


Write User Account Address Attributes

Description
Configures address-related attributes for a user account.

Script Code

Set objUser = GetObject _
   ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")

objUser.Put "streetAddress", "Building 43" & _
  VbCrLf & "One Microsoft Way"
objUser.Put "l", "Redmond"
objUser.Put "st", "Washington"
objUser.Put "postalCode", "98053"
objUser.Put "c", "US"
objUser.Put "postOfficeBox", "2222"

objUser.SetInfo


Write User Account Properties

Description
Configures general attributes for a user account.

Script Code

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")

objUser.Put "userPrincipalName", "MyerKen@fabrikam.com"
objUser.Put "sAMAccountName", "MyerKen01"
objUser.Put "userWorkstations", "wks1,wks2,wks3"

objUser.SetInfo


Add a New Record to a Database

Description
Demonstration script that retrieves sound card information for a computer, and then saves that information to an ADO database with the DSN "Inventory."

Script Code

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
Set colSoundCards = GetObject("winmgmts:").ExecQuery _
    ("Select * from Win32_SoundDevice")
For Each objSoundCard in colSoundCards
    objRecordset.AddNew
    objRecordset("ComputerName") = objSoundCard.SystemName
    objRecordset("Manufacturer") = objSoundCard.Manufacturer
    objRecordset("ProductName") = objSoundCard.ProductName
    objRecordset.Update
Next
objRecordset.Close
objConnection.Close


Add a Template to the Windows Explorer New Menu

Description
Demonstrates how to add VBScript Script File to the New context menu in Windows Explorer. Requires a script template named Template.vbs to be in the \Windows\System32\ShellExt folder (on Windows XP and Windows .NET Server), or in the \Winnt\ShellNew folder (Windows 2000).

Script Code

Set objShell = WScript.CreateObject("WScript.Shell")
objShell.RegWrite "HKCR\.VBS\ShellNew\FileName","template.vbs"


Add Elements to a Dictionary

Description
Demonstration script that adds three key-item pairs to a Script Runtime Dictionary. Script must be run on the local computer.

Script Code

Set objDictionary = CreateObject("Scripting.Dictionary")
objDictionary.Add "Printer 1", "Printing"
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"


Connect to an ADO Database

Description
Demonstration script that connects to an ADO database with the DSN "Inventory."

Script Code

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


Create Script Documentation Using Script Comments

Description
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 '*.

Script Code

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


Determine the Number of Items in a Dictionary

Description
Demonstration script that counts the number of key-item pairs in a Script Runtime Dictionary. Script must be run on the local computer.

Script Code

Set objDictionary = CreateObject("Scripting.Dictionary")
objDictionary.Add "Printer 1", "Printing"
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"
Wscript.Echo objDictionary.Count


Find a Record in a Recordset

Description
Searches an ADO database with a DSN of "Inventory" looking for a specific computer record.

Script Code

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


Remove All Elements from a Dictionary

Description
Demonstration script that deletes all the key-item pairs from a Script Runtime Dictionary. Script must be run on the local computer.

Script Code

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


Remove Debugging Comments

Description
Demonstrates the use of the FileSystemObject as a way to remove debugging comments from a script. Requires comments to have been marked as '* BUG.

Script Code

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


Remove One Element from a Dictionary

Description
Demonstration script that deletes a specific key-item pair from a Script Runtime Dictionary. Script must be run on the local computer.

Script Code

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


Update Records in a Recordset

Description
Demonstration script that updates sound card information for a computer named Webserver. Requires an ADO Database with a DSN of "Inventory."

Script Code

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


Verify the Existence of a Dictionary Key

Description
Demonstration script that verifies the existence of a particular key within a Script Runtime Dictionary. Script must be run on the local computer.

Script Code

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