Active Directory Scripting
http://www.microsoft.com/technet/scriptcenter/guide/sas_ads_overview.mspx?mfr=true ——————————————————————————————–

rem this code creates a user account with the common name MyerKen:

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

Attribute Default Setting
pwdLastSet User must change password at next logon

userAccountControl Password Not Required

userAccountControl Account Disabled

———————————————————————
Setting a User Account Password

Set objUser = GetObject _
("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
objUser.SetPassword "i5A2sj*!"

———————————————————————
Changing a User Account Password

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

———————————————————————-
Displaying Password Attributes Available from the LDAP Provider and the userAccountControl Attribute

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=NA,dc=fabrikam,dc=com")
intUAC = objUser.Get("userAccountControl")

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
Next

———————————————–
Determining When a Password Was Last Set

Set objUser = GetObject _
("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
dtmValue = objUser.PasswordLastChanged
Wscript.Echo "Password was last set: " & dtmValue
————————————————
Disabling a Password-Related Flag in userAccountControl

Const ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = &H80

Set objUser = GetObject _
("LDAP://cn=MyerKen,ou=Management,dc=NA,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

—————————————————
Enabling the User must change password at next logon Option

Set objUser = GetObject _
("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
objUser.Put "pwdLastSet", 0
objUser.SetInfo

————————————————–
Disabling the User must change password at next logon Option

Set objUser = GetObject _
("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
objUser.Put "pwdLastSet", -1
objUser.SetInfo

——————————————————–
Enabling a User Account by Modifying the ADS_UF_ACCOUNTDISABLE Flag

Const ADS_UF_ACCOUNTDISABLE = 2

Set objUser = GetObject _
("LDAP://cn=MyerKen,ou=Management,dc=NA,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

————————————————————-
Disabling a User Account by Modifying the ADS_UF_ACCOUNTDISABLE Flag

Const ADS_UF_ACCOUNTDISABLE = 2

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

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

—————————————————————-
Checking the Value of the ADS_UF_ACCOUNTDISABLE Flag
Const ADS_UF_ACCOUNTDISABLE = 2

Set objUser = GetObject _
("LDAP://cn=MyerKen,ou=Management,dc=NA,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

———————————————————–
Reading Attributes on the General Properties Page

On Error Resume Next
Set objUser = GetObject _
("LDAP://cn=MyerKen,ou=Management,dc=NA,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
Next

————————————————-
Writing Values to Attributes

Const ADS_PROPERTY_UPDATE = 2
Set objUser = GetObject _
("LDAP://cn=MyerKen,ou=Management,dc=NA,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) 707-9795"
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("(425) 707-9794", "(425) 707-9790")

objUser.PutEx ADS_PROPERTY_UPDATE, _
"url", Array("http://www.fabrikam.com/management")
objUser.SetInfo

———————————————
Appending an Entry to a Multivalued Attribute

Const ADS_PROPERTY_APPEND = 3

Set objUser = GetObject _
("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")

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

objUser.SetInfo
———————————————–
Deleting an Entry in a Multivalued Attribute

Const ADS_PROPERTY_DELETE = 4

Set objUser = GetObject _
("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")

objUser.PutEx ADS_PROPERTY_DELETE, _
"otherTelephone", Array("(425) 707-9790")
objUser.PutEx ADS_PROPERTY_DELETE, _
"initials", Array("E.")

objUser.SetInfo

———————————————-

Removing Entries in Selected Single-valued and Multivalued Attributes

Const ADS_PROPERTY_CLEAR = 1

Set objUser = GetObject _
("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")

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

objUser.SetInfo
———————————————
Copying the Attributes from One User Account to Another

Set objOU = GetObject("LDAP://ou=HR,dc=NA,dc=fabrikam,dc=com")
Set objUser = objOU.Create("User", "cn=BarrAdam")
objUser.Put "sAMAccountName", "barradam"
objUser.SetInfo

Set objUserTemplate = _
GetObject("LDAP://cn=HRUser,ou=HR,dc=fabrikam,dc=com")
arrAttributes = _
Array("description", "wWWHomePage", "department", "company")
objUserTemplate.GetInfoEx arrAttributes, 0

For Each strAttrib in arrAttributes
strValue = objUserTemplate.Get(strAttrib)
objUser.Put strAttrib, strValue
Next

objUser.SetInfo

———————————————-
Moving a User Account to a Different OU Within the Same Domain

Set objOU = GetObject("LDAP://ou=Sales,dc=NA,dc=fabrikam,dc=com")

objOU.MoveHere _
"LDAP://cn=BarrAdam,ou=HR,dc=NA,dc=fabrikam,dc=com", "cn=barradam"

—————————————————
Renaming a User Account Within the Same OU
Set objOU = GetObject("LDAP://ou=Sales,dc=NA,dc=fabrikam,dc=com")

objOU.MoveHere _
"LDAP://cn=BarrAdam,ou=Sales,dc=NA,dc=fabrikam,dc=com", "cn=LewJudy"

—————————————————
Renaming and Moving a User Account to a Different OU

Set objOU = GetObject("LDAP://ou=Management,dc=NA,dc=fabrikam,dc=com")

objOU.MoveHere _
"LDAP://cn=LewJudy,ou=Sales,dc=NA,dc=fabrikam,dc=com", _
"cn=AckermanPilar"

—————————————————
Moving a User Account to an OU in a Different Domain

Set objOU = GetObject("LDAP://ou=Management,dc=NA,dc=fabrikam,dc=com")

objOU.MoveHere _
"LDAP://cn=AckermanPilar,ou=Management,dc=fabrikam,dc=com", _
vbNullString

If you need to move an OU or another container (and all of the objects within the container)
to a different domain in the forest, use the Movetree.exe command-line tool.
For information about this tool, install the Windows Support Tools from the SupportTools
folder on the Windows 2000 Server installation CD. Following installation, from a command
prompt, type movetree /? for syntax and Movetree examples.

—————————————————

Deleting an Active Directory User Account

Set objOU = GetObject("LDAP://ou=Management,dc=NA,dc=fabrikam,dc=com")
objOU.Delete "User", "cn=MyerKen"

————————————————–
Performing a Search to Display All Names in an OU

Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"

Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection

objCommand.CommandText = _
"<LDAP://ou=Management,dc=NA,dc=fabrikam,dc=com>;;name;onelevel"
Set objRecordSet = objCommand.Execute

While Not objRecordset.EOF
Wscript.Echo objRecordset.Fields("name")
objRecordset.MoveNext
Wend

objConnection.Close
————————————————-
Using SQL Syntax to Perform a Search to Display All Names in an OU

Const ADS_SCOPE_ONELEVEL = 1

Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"

Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
objCommand.Properties("searchscope") = ADS_SCOPE_ONELEVEL

objCommand.CommandText = _
"SELECT name FROM 'LDAP://ou=Management,dc=NA,dc=fabrikam,dc=com'"

Set objRecordSet = objCommand.Execute

While Not objRecordset.EOF
Wscript.Echo objRecordset.Fields("name")
objRecordset.MoveNext
Wend

objConnection.Close
———————————————–
Performing a Search to Display the Names of User Account Types That Are Security Principals in an OU

Set objConnection = CreateObject("ADODB.Connection") objConnection.Open "Provider=ADsDSOObject;"
Set objCommand = CreateObject("ADODB.Command") objCommand.ActiveConnection = objConnection
objCommand.CommandText = _ "<LDAP://ou=Management,dc=NA,dc=fabrikam,dc=com>;" & _
"(&(objectCategory=person)(objectClass=user));" & _
"name;onelevel" Set objRecordSet = objCommand.Execute While Not objRecordset.EOF _
Wscript.Echo objRecordset.Fields("name") objRecordset.MoveNext Wend objConnection.Close

——————————————————-
Performing a Search to Display the Names of User Account Types That Are Security Principals in a Forest

Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"

Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection

objCommand.CommandText = _
"<GC://dc=fabrikam,dc=com>;" & _
"(&(objectCategory=person)(objectClass=user));" & _
"name;subtree"

Set objRecordSet = objCommand.Execute

While Not objRecordset.EOF
Wscript.Echo objRecordset.Fields("name")
objRecordset.MoveNext
Wend

objConnection.Close
———————————————
Performing a Search to Determine Whether a User Account Name Is in Use

Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"

Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection

objCommand.CommandText = _
"<GC://dc=fabrikam,dc=com>;" & _
"(&(objectCategory=person)(objectClass=user)" & _
"(sAMAccountName=myerken));" & _
"sAMAccountName, distinguishedName;subtree"

Set objRecordSet = objCommand.Execute

If objRecordSet.RecordCount = 0 Then
Wscript.Echo "The sAMAccountName is not in use."
Else
While Not objRecordset.EOF
Wscript.Echo "sAMAccountName = " & _
objRecordset.Fields("sAMAccountName")
Wscript.Echo "distinguishedName = " & _
objRecordset.Fields("distinguishedName")
objRecordset.MoveNext
Wend
End If

objConnection.Close

——————————————
Using the Not Present Operator to Display All User Accounts with an Empty Attribute

Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"

Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection

objCommand.CommandText = _
"<GC://dc=fabrikam,dc=com>;" & _
"(&(objectCategory=person)(!mail=*));" & _
"distinguishedName;subtree"

Set objRecordSet = objCommand.Execute

If objRecordset.EOF Then
Wscript.Echo _
"All user accounts contain a value for the mail attribute."
Else
Wscript.Echo "User account(s) without a mail value:"
While Not objRecordset.EOF
Wscript.Echo objRecordset.Fields("distinguishedName")
objRecordset.MoveNext
Wend
End If

objConnection.Close

————————————————-
Using IsNull to Display All User Accounts with an Empty Attribute

Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"

Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection

objCommand.CommandText = _
"<GC://dc=fabrikam,dc=com>;" & _
"(objectCategory=person);" & _
"distinguishedName,mail;subtree"

Set objRecordSet = objCommand.Execute
blnNoEmptyMailAttribute = True
While Not objRecordset.EOF
If IsNull(objRecordset.Fields("mail")) Then
blnNoEmptyMailAttribute = False
Wscript.Echo objRecordset.Fields("distinguishedName")
End If
objRecordset.MoveNext
If blnNoEmptyMailAttribute Then
Wscript.Echo _
"All user accounts contain a value for the mail attribute."
End If
Wend

objConnection.Close

————————————
Searching for User Accounts That Contain a Similar Value in an Attribute

Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"

Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection

objCommand.CommandText = _
"<GC://dc=fabrikam,dc=com>;" & _
"(&(objectCategory=person)(telephoneNumber=707*));" & _
"distinguishedName,telephoneNumber;subtree"

Set objRecordSet = objCommand.Execute

If objRecordset.EOF Then
Wscript.Echo _
"No user accounts found with this area code."
Else
Wscript.Echo "User account(s) with the specified area code:"
While Not objRecordset.EOF
Wscript.Echo objRecordset.Fields("distinguishedName") & ": " & _
objRecordset.Fields("telephoneNumber")
objRecordset.MoveNext
Wend
End If

objConnection.Close

————————————-
Searching for User Accounts Containing a Particular Multivalued Attribute

Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"

Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection

objCommand.CommandText = _
"<LDAP://ou=Management,dc=NA,dc=fabrikam,dc=com>;" & _
"(&(objectCategory=person)(otherTelephone=*));" & _
"cn,otherTelephone;onelevel"

Set objRecordSet = objCommand.Execute

While Not objRecordset.EOF
Wscript.Echo objRecordset.Fields("cn") & VbCr
For Each varRecord in objRecordset.Fields("otherTelephone").Value
Wscript.stdOut.Write varRecord & " "
Next
Wscript.Echo VbCrLf
objRecordset.MoveNext
Wend

objConnection.Close

—————————————
Sorting a Result Set from a Search of the Active Directory

Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"

Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection

objCommand.Properties("Sort On") = "physicalDeliveryOfficeName"

objCommand.CommandText = _
"<LDAP://dc=NA,dc=fabrikam,dc=com>;" & _
"(objectCategory=person);" & _
"distinguishedName,physicalDeliveryOfficeName;subtree"

Set objRecordSet = objCommand.Execute

While Not objRecordset.EOF
Wscript.Echo objRecordset.Fields("distinguishedName") & ": " & _
objRecordset.Fields("physicalDeliveryOfficeName")
objRecordset.MoveNext
Wend

objConnection.Close

———————————–
Modifying Multiple User Accounts Using the Result Set Returned by a Search

Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"

Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection

objCommand.CommandText = _
"<LDAP://dc=NA,dc=fabrikam,dc=com>;" & _
"(&(objectCategory=person)(objectClass=user));" & _
"ADsPath;subtree"

Set objRecordSet = objCommand.Execute

While Not objRecordset.EOF
strADsPath = objRecordset.Fields("ADsPath")
Set objUser = GetObject(strADsPath)
objUser.Put "company", "Fabrikam"
objUser.SetInfo
objRecordset.MoveNext
Wend

Wscript.Echo objRecordSet.RecordCount & " user accounts modified."

objConnection.Close

———————————
Modifying Multiple User Accounts in a Container by Using Enumeration
Set objOU = GetObject("LDAP://ou=Management,dc=NA,dc=fabrikam,dc=com")

objOU.Filter = Array("user")

For Each objUser In objOU
Wscript.Echo "Modified " & objUser.Name
objUser.Put "company", "Fabrikam"
objUser.SetInfo
Wscript.Echo "The new company name is: " & _
objUser.Get("company")
Next

————————————–
Computers:

Retrieving System Information

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

————————

Retrieving BIOS Information

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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 Each intCharacteristic in objBIOS.BiosCharacteristics
Wscript.Echo "BIOS Characteristics: " & intCharacteristic
Next
Next

——————————–
Retrieving Identifying Information
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

———————————–
Inventorying Computer Hardware
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colMice = objWMIService.ExecQuery _
("SELECT * FROM Win32_PointingDevice")
For Each objMouse in colMice
Wscript.Echo "Hardware Type: " & objMouse.HardwareType
Wscript.Echo "Number of Buttons: " & objMouse.NumberOfButtons
Wscript.Echo "Status: " & objMouse.Status
Wscript.Echo "PNP Device ID: " & objMouse.PNPDeviceID
Next

———————————
Identifying Computer Chassis Type

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colChassis = objWMIService.ExecQuery _
("SELECT * FROM Win32_SystemEnclosure")
For Each objChassis in colChassis
For Each intType in objChassis.ChassisTypes
Wscript.Echo intType
Next
Next

———————————–
Identifying the Name and Version Number of the Operating System

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colOperatingSystems = objWMIService.ExecQuery _
("SELECT * FROM Win32_OperatingSystem")
For Each objOperatingSystem in colOperatingSystems
Wscript.Echo objOperatingSystem.Caption, objOperatingSystem.Version
Next

————————————-

Retrieving the Properties of the Operating System

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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 "Install Date: " & objOperatingSystem.InstallDate
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
Next

——————————————-

Identifying the Latest Installed Service Pack

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colOperatingSystems = objWMIService.ExecQuery _
("SELECT * FROM Win32_OperatingSystem")
For Each objOperatingSystem in colOperatingSystems
Wscript.Echo objOperatingSystem.ServicePackMajorVersion _
& "." & objOperatingSystem.ServicePackMinorVersion
Next

——————————————
Enumerating Installed Hot Fixes

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

—————————————–
Enumerating WMI Settings

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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 Each strMOF in objWMISetting.AutorecoverMofs
Wscript.Echo "Autorecover MOF: " & strMOF
Next
Next

———————————-
Configuring WMI Settings

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colWMISettings = objWMIService.ExecQuery _
("SELECT * FROM Win32_WMISetting")
For Each objWMISetting in colWMISettings
objWMISetting.BackupInterval = 60
objWMISetting.LoggingLevel = 2
objWMISetting.Put_
Next

——————————–
Enumerating Installed Software

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.CreateTextFile("c:scriptssoftware.tsv", True)
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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.InstallLocation & vbtab & _
objSoftware.InstallState & vbtab & _
objSoftware.Name & vbtab & _
objSoftware.PackageCache & vbtab & _
objSoftware.SKUNumber & vbtab & _
objSoftware.Vendor & vbtab & _
objSoftware.Version
Next
objTextFile.Close

———————————
Enumerating Installed Software Features
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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 "Last Use: " & objFeature.LastUse
Wscript.Echo "Name: " & objFeature.Name
Wscript.Echo "Product Name: " & objFeature.ProductName
Wscript.Echo "Vendor: " & objFeature.Vendor
Wscript.Echo "Version: " & objFeature.Version
Next

————————————
Installing Software
Const ALL_USERS = True
Set objService = GetObject("winmgmts:")
Set objSoftware = objService.Get("Win32_Product")
errReturn = objSoftware.Install("c:scriptsdatabase.msi", , ALL_USERS)

————————————
Installing Software on a Remote Computer

strComputer = "atl-dc-02"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set objSoftware = objWMIService.Get("Win32_Product")
errReturn = objSoftware.Install("c:scriptsdatabase.msi",,True)
Wscript.Echo errReturn

————————————————
Upgrading Software
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colSoftware = objWMIService.ExecQuery _
("SELECT * FROM Win32__Product WHERE Name = 'Personnel Database'")
For Each objSoftware in colSoftware
errReturn = objSoftware.Upgrade("c:scriptsdatabase2.msi")
Next

———————————————-
Removing Software

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colSoftware = objWMIService.ExecQuery _
("SELECT * FROM Win32_Product WHERE Name = 'Personnel database'")
For Each objSoftware in colSoftware
objSoftware.Uninstall()
Next
————————————————-
Enumerating Startup Options

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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 Each strOption in objStartupCommand.SystemStartupOptions
Wscript.Echo "Startup Options: " & strOption
Next
Wscript.Echo "Startup Setting: " & _
objStartupCommand.SystemStartupSetting
Next

————————————————-
Configuring the System Startup Delay
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colStartupCommands = objWMIService.ExecQuery _
("SELECT * FROM Win32_ComputerSystem")
For Each objStartupCommand in colStartupCommands
objStartupCommand.SystemStartupDelay = 10
objStartupCommand.Put_
Next

After running this script, the Boot.ini will look similar to the following:

[boot loader]
timeout=10
default=multi(0)disk(0)rdisk(0)partition(1)WINNT

————————————————-
Enumerating Computer Startup Commands

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

————————————————
Enumerating the Recovery Configuration Options for a Computer

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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 "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
Next

————————————————–
Modifying the Recovery Configuration on a Computer

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colRecoveryOptions = objWMIService.ExecQuery _
("SELECT * FROM Win32_OSREcoveryConfiguration")
For Each objOption in colRecoveryOptions
objOption.DebugFilePath = "c:scriptsmemory.dmp"
objOption.OverWriteExistingDebugFile = False
objOption.Put_
Next

———————————————–
Querying the System Event Log for Stop Events
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

———————————————
Shutting Down a Computer
Const SHUTDOWN = 1
strComputer = "."
Set objWMIService = GetObject("winmgmts: {(Shutdown)}" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colOperatingSystems = objWMIService.ExecQuery _
("SELECT * FROM Win32_OperatingSystem")
For Each objOperatingSystem in colOperatingSystems
ObjOperatingSystem.Win32Shutdown(SHUTDOWN)
Next

———————————————-
Restarting a Computer

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate,(Shutdown)}!" & _
strComputer & "rootcimv2")
Set colOperatingSystems = objWMIService.ExecQuery _
("SELECT * FROM Win32_OperatingSystem")
For Each objOperatingSystem in colOperatingSystems
objOperatingSystem.Reboot()
Next

————————————————
Monitoring Changes in Power Status
Set colMonitoredEvents = GetObject("winmgmts:")._
ExecNotificationQuery("SELECT * FROM Win32_PowerManagementEvent")
Do
Set strLatestEvent = colMonitoredEvents.NextEvent
Wscript.Echo strLatestEvent.EventType
Loop

————————————————–
Retrieving Basic Computer Information Using ADSystemInfo

Set objSysInfo = CreateObject("ADSystemInfo")
Wscript.Echo "User name: " & objSysInfo.UserName
Wscript.Echo "Computer name: " & objSysInfo.ComputerName
Wscript.Echo "Site name: " & objSysInfo.SiteName
Wscript.Echo "Domain short name: " & objSysInfo.DomainShortName
Wscript.Echo "Domain DNS name: " & objSysInfo.DomainDNSName
Wscript.Echo "Forest DNS name: " & objSysInfo.ForestDNSName
Wscript.Echo "PDC role owner: " & objSysInfo.PDCRoleOwner
Wscript.Echo "Schema role owner: " & objSysInfo.SchemaRoleOwner
Wscript.Echo "Domain is in native mode: " & objSysInfo.IsNativeMode

——————————————————–
Creating a Computer Account in Active Directory

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

———————————————–
Deleting a Computer Account
set objComputer = GetObject _
("LDAP://CN=Workstation4, CN=Computers, DC=fabrikam, DC=com")
objComputer.DeleteObject (0)

——————————————–
Deleting Specified Computer Accounts
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 distinguishedName, operatingSystemVersion FROM " _
& "'LDAP://DC=fabrikam,DC=com' WHERE objectClass='computer' " _
& "AND operatingSystemVersion = '4.0'"
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
strComputer = objRecordSet.Fields("distinguishedName").Value
Set objComputer = GetObject("LDAP://" & strComputer & "")
objComputer.DeleteObject (0)
objRecordSet.MoveNext
Loop

————————————–
Enumerating Computer Account Attributes
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

————————————-
Changing the Computer Account Location Attribute

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

————————————–
Renaming a Computer Account

Set objNewOU = GetObject("LDAP://OU=Finance, DC=fabrikam, DC=com")
Set objMoveComputer = objNewOU.MoveHere _
("LDAP://CN=Workstation4, OU=Finance, DC=fabrikam, DC=com", _
"CN=Workstation5")

—————————————-
Moving Computer Accounts

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

—————————————-
Resetting a Computer Account Password

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

—————————————
Enumerating All the Computer Accounts in Active Directory
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

——————————-
Locating Computers Based on Computer Account Attributes
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.0 (2195)'"
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

——————————————-

Identifying the Basic Role of a Computer

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colComputers = objWMIService.ExecQuery _
("SELECT * 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
Next

————————————-
Identifying Computer Roles Based on Services

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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

————————————-
Enumerating Domain Controllers

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 distinguishedName FROM " _
& "'LDAP://cn=Configuration,DC=fabrikam,DC=com' " _
& "WHERE objectClass='nTDSDSA'"
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("distinguishedName").Value
objRecordSet.MoveNext
Loop

———————————-
Identifying the Current Domain Controller

Set objDomain = GetObject("LDAP://RootDSE")
objDC = objDomain.Get("dnsHostName")
Wscript.Echo objDC

—————————————
Identifying FSMO Roles

Set objADOConnection = CreateObject("ADODB.Connection")
objADOConnection.Provider = "ADSDSOObject"
objADOConnection.Open "ADs Provider"
strADOQueryString = _
"<LDAP://DC=fabrikam,DC=com>;(&(objectClass=domainDNS)" _
& "(fSMORoleOwner=*));adspath;subtree"
Set RSObj = objADOConnection.Execute(strADOQueryString)
Set objFSMO = GetObject(RSObj.Fields(0).Value)
Set objNTDS = GetObject("LDAP://" & objFSMO.fSMORoleOwner)
Set objComputer = GetObject(objNTDS.Parent)
WScript.Echo "The Primary Domain Controller FSMO is: " & _
objComputer.dnsHostName

—————————————-
Identifying Global Catalog Servers

On Error Resume Next
Set objRoot = GetObject("LDAP://atl-dc-01/RootDSE")
objDSServiceDN = objRoot.Get("dsServiceName")
Set objDSRoot = GetObject("LDAP://atl-dc-02/" & objDSServiceDN )
blnCurrentOptions = objDSRoot.Get("options")
If blnCurrentOptions Then
Wscript.Echo "This computer is a global catalog server."
Else
Wscript.Echo "This computer is not a global catalog server."
End If

————————————-
Enabling a Global Catalog Server

On Error Resume Next
Set objRoot = GetObject("LDAP://atl-dc-01/RootDSE")
objDSServiceDN = objRoot.Get("dsServiceName")
Set objDSRoot = GetObject("LDAP://atl-dc-01/" & objDSServiceDN )
blnCurrentOptions = objDSRoot.Get("Options")
objDSRoot.Put "options" , 1
objDSRoot.Setinfo

————————————
Disabling a Global Catalog Server

On Error Resume Next
Set objRoot = GetObject("LDAP://atl-dc-01/RootDSE")
objDSServiceDN = objRoot.Get("dsServiceName")
Set objDSRoot = GetObject("LDAP://atl-dc-01/" & objDSServiceDN )
blnCurrentOptions = objDSRoot.Get("Options")
objDSRoot.Put "options" , 0
objDSRoot.Setinfo
————————————
Enumerating Physical Disk Drive Properties

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

——————————————-
Enumerating Logical Disk Drive Properties

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colDisks = objWMIService.ExecQuery _
("SELECT * FROM Win32_LogicalDisk")
For each objDisk in colDisks
Wscript.Echo "Compressed: " & objDisk.Compressed
Wscript.Echo "Description: " & objDisk.Description
Wscript.Echo "Device ID: " & objDisk.DeviceID
Wscript.Echo "Drive Type: " & objDisk.DriveType
Wscript.Echo "FileSystem: " & objDisk.FileSystem
Wscript.Echo "FreeSpace: " & objDisk.FreeSpace
Wscript.Echo "MediaType: " & objDisk.MediaType
Wscript.Echo "Name: " & objDisk.Name
Wscript.Echo "Size: " & objDisk.Size
Wscript.Echo "SupportsFileBasedCompression: " & _
objDisk.SupportsFileBasedCompression
Wscript.Echo "SystemName: " & objDisk.SystemName
Wscript.Echo "VolumeName: " & objDisk.VolumeName
Wscript.Echo "VolumeSerialNumber: " & _
objDisk.VolumeSerialNumber
Next

——————————————
Identifying Drives and Drive Types

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

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colDrives = objWMIService.ExecQuery _
("SELECT * FROM Win32_LogicalDisk WHERE DeviceID = 'C:'")
For Each objDrive in colDrives
objDrive.VolumeName = "Finance Volume"
objDrive.Put_
Next

———————————————–
Enumerating Free Disk Space

Const HARD_DISK = 3
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colDisks = objWMIService.ExecQuery _
("SELECT * FROM Win32_LogicalDisk WHERE DriveType = " _
& HARD_DISK & "")
For Each objDisk in colDisks
Wscript.Echo "Device ID: " & objDisk.DeviceID
Wscript.Echo "Free Disk Space: " & objDisk.FreeSpace
Next

——————————————–
Using Disk Quotas to Enumerate Disk Space by User
Set colDiskQuotas = CreateObject("Microsoft.DiskQuota.1")
colDiskQuotas.Initialize "C:", True
For Each objUser in colDiskQuotas
Wscript.Echo "Logon name: " & objUser.LogonName
Wscript.Echo "Quota used: " & objUser.QuotaUsed
Next

———————————————-
Monitoring Free Disk Space

Const LOCAL_HARD_DISK = 3
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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

—————————————
Enumerating Disk Quota Settings

Set colDiskQuotas = CreateObject("Microsoft.DiskQuota.1")
colDiskQuotas.Initialize "C:", True
If colDiskQuotas.QuotaState = 2 Then
Wscript.Echo "Quota state: Enabled and enforced"
ElseIf colDiskQuotas.QuotaState = 1 Then
Wscript.Echo "Quota state: Enabled but not enforced"
Else
Wscript.Echo "Quota state: Disabled"
End If
Wscript.Echo "Default quota limit: " & colDiskQuotas.DefaultQuotaLimit
Wscript.Echo "Default warning limit: " & _
colDiskQuotas.DefaultQuotaThreshold
Wscript.Echo "Record quota violations in event log: " & _
colDiskQuotas.LogQuotaLimit
Wscript.Echo "Record warnings in event log: " & _
colDiskQuotas.LogQuotaThreshold

—————————————-
Enabling Disk Quotas

Const ENABLE_QUOTAS = 2
Set colDiskQuotas = CreateObject("Microsoft.DiskQuota.1")
colDiskQuotas.Initialize "C:", True
colDiskQuotas.QuotaState = ENABLE_QUOTAS

—————————————–
Configuring Disk Quota Settings

Set colDiskQuotas = CreateObject("Microsoft.DiskQuota.1")
colDiskQuotas.Initialize "C:", True
colDiskQuotas.DefaultQuotaLimit = 10000000

——————————————–
Enumerating Disk Quotas
Set colDiskQuotas = CreateObject("Microsoft.DiskQuota.1")
colDiskQuotas.Initialize "C:", True
For Each objUser in colDiskQuotas
Wscript.Echo "Logon name: " & objUser.LogonName
Wscript.Echo "Quota limit: " & objUser.QuotaLimit
Wscript.Echo "Quota threshold: " & objUser.QuotaThreshold
Wscript.Echo "Quota used: " & objUser.QuotaUsed
Next

——————————————
Adding a New Disk Quota Entry

Set colDiskQuotas = CreateObject("Microsoft.DiskQuota.1")
colDiskQuotas.Initialize "C:", True
Set objUser = colDiskQuotas.AddUser("fabrikamjsmith")
Wscript.Sleep 5000
Set objUser = colDiskQuotas.FindUser("fabrikamjsmith")
objUser.QuotaLimit = 50000000

——————————————
Modifying a Disk Quota Entry

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

——————————————–
Deleting a Disk Quota Entry

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

——————————————-
Identifying the File System Type
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colDisks = objWMIService.ExecQuery _
("SELECT * FROM Win32_LogicalDisk")
For Each objDisk in colDisks
Wscript.Echo "Device ID: " & objDisk.DeviceID
Wscript.Echo "File System: " & objDisk.FileSystem
Next

—————————————————–
Enumerating NTFS Properties
Const HKEY_LOCAL_MACHINE = &H80000002

strComputer = "."
Set objRegistry = GetObject _
("winmgmts:{impersonationLevel=impersonate}!" & _
strComputer & "rootdefault:StdRegProv")

strKeyPath = "SystemCurrentControlSetControlFileSystem"
strValueName = "NtfsDisable8dot3NameCreation"
objRegistry.GetDWORDValue _
HKEY_LOCAL_MACHINE,strKeyPath,strValueName,dwValue

If IsNull(dwValue) Then
Wscript.Echo "No value set for disabling 8.3 file name creation."
ElseIf dwValue = 1 Then
WScript.Echo "No 8.3 file names will be created for new files."
ElseIf dwValue = 0 Then
Wscript.Echo "8.3 file names will be created for new files."
End If

strValueName = "NtfsAllowExtendedCharacterIn8Dot3Name"
objRegistry.GetDWORDValue _
HKEY_LOCAL_MACHINE,strKeyPath,strValueName,dwValue

If IsNull(dwValue) Then
Wscript.Echo "No value set for allowing extended characters in " _
& " 8.3 file names."
ElseIf dwValue = 1 Then
WScript.Echo "Extended characters are permitted in 8.3 file names."
ElseIf dwValue = 0 Then
Wscript.Echo "Extended characters not permitted in 8.3 file names."
End If

strValueName = "NtfsMftZoneReservation"
objRegistry.GetDWORDValue _
HKEY_LOCAL_MACHINE,strKeyPath,strValueName,dwValue

If IsNull(dwValue) Then
Wscript.Echo "No value set for reserving the MFT zone."
ElseIf dwValue = 1 Then
WScript.Echo _
"One-eighth of the disk has been reserved for the MFT zone."
ElseIf dwValue = 2 Then
Wscript.Echo "One-fourth of the disk reserved for the MFT zone."
ElseIf dwValue = 3 Then
Wscript.Echo "Three-eighths of the disk reserved for the MFT zone."
ElseIf dwValue = 4 Then
Wscript.Echo "One half of the disk reserved for the MFT zone."
End If

strValueName = "NtfsDisableLastAccessUpdate"
objRegistry.GetDWORDValue _
HKEY_LOCAL_MACHINE,strKeyPath,strValueName,dwValue

If IsNull(dwValue) Then
Wscript.Echo "No value set for disabling the last access update " _
& "for files and folder."
ElseIf dwValue = 1 Then
WScript.Echo _
"The last access timestamp will not be updated on files " _
& "and folders."
ElseIf dwValue = 0 Then
Wscript.Echo "The last access timestamp updated on files and " _
& "folders."
End If

strValueName = "Win31FileSystem"
objRegistry.GetDWORDValue _
HKEY_LOCAL_MACHINE,strKeyPath,strValueName,dwValue

If IsNull(dwValue) Then
Wscript.Echo "No value set for using long file names and " _
& "timestamps."
ElseIf dwValue = 1 Then
WScript.Echo "Long file names and extended timestamps are used."
ElseIf dwValue = 0 Then
Wscript.Echo "Long file names and extended timestamps are not used."
End If

—————————————–
Modifying File System Properties
const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."

Set objRegistry = GetObject _
("winmgmts:{impersonationLevel=impersonate}!" & _
strComputer & "rootdefault:StdRegProv")

strKeyPath = "SystemCurrentControlSetControlFileSystem"
strValueName = "Win31FileSystem"
dwValue = 1
objRegistry.SetDWORDValue _
HKEY_LOCAL_MACHINE,strKeyPath,strValueName,dwValue
——————————————-
Monitoring Page File Use

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colPageFiles = objWMIService.ExecQuery _
("SELECT * FROM Win32_PageFileUsage")
For each objPageFile in colPageFiles
Wscript.Echo "Allocated Base Size: " & objPageFile.AllocatedBaseSize
Wscript.Echo "CurrentUsage: " & objPageFile.CurrentUsage
Wscript.Echo "Description: " & objPageFile.Description
Wscript.Echo "InstallDate: " & objPageFile.InstallDate
Wscript.Echo "Name: " & objPageFile.Name
Wscript.Echo "PeakUsage: " & objPageFile.PeakUsage
Next

——————————————
Configuring Page File Properties

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colPageFiles = objWMIService.ExecQuery _
("SELECT * FROM Win32_PageFileSetting")
For Each objPageFile in colPageFiles
objPageFile.InitialSize = 300
objPageFile.MaximumSize = 600
objPageFile.Put_
Next

—————————————–
Retrieving Folder Properties

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

————————————–
Enumerating All the Folders on a Computer
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colFolders = objWMIService.ExecQuery("SELECT * FROM Win32_Directory")
For Each objFolder in colFolders
Wscript.Echo objFolder.Name
Next

———————————————
Enumerating the Subfolders of a Folder
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

——————————————
Enumerating a Specific Set of Folders

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colFiles = objWMIService.ExecQuery _
("SELECT * FROM Win32_Directory WHERE Hidden = True")
For Each objFile in colFiles
Wscript.Echo objFile.Name
Next

—————————————
Enumerating Folders Using Dates

dtmTargetDate = "20020301000000.000000-420"
strComputer = "."
Set objWMIService = GetObject _
("winmgmts:" & "!" & strComputer & "rootcimv2")
Set colFolders = objWMIService.ExecQuery _
("SELECT * FROM Win32_Directory WHERE CreationDate > '" & _
dtmtargetDate & "'")
For Each objFolder in colFolders
Wscript.Echo objFolder.Name
Next

————————————-
Enumerating Special Folders

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

—————————————
Enumerating Installed Administrative Tools

Const ADMINISTRATIVE_TOOLS = &H2f&
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(ADMINISTRATIVE_TOOLS)
Set colTools = objFolder.Items
For Each objTool in colTools
Wscript.Echo objTool
Next

—————————————–
Using the Browse For Folder Dialog Box

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 & "rootcimv2")
Set colFiles = objWMIService.ExecQuery _
("SELECT * FROM Win32_Directory WHERE Name = '" & objPath & "'")
For Each objFile in colFiles
Wscript.Echo "Readable: " & objFile.Readable
Next

———————————-
renaming folders
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

——————————–
Moving Folders Using WMI

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colFolders = objWMIService.ExecQuery _
("SELECT * FROM Win32_Directory WHERE Name = 'c:Scripts'")
For Each objFolder in colFolders
errResults = objFolder.Rename("C:AdminsDocumentsArchiveVBScript")
Wscript.Echo errResults
Next

——————————-
Copying Folders Using WMI

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colFolders = objWMIService.ExecQuery _
"SELECT * FROM Win_32 Directory" WHERE Name = 'c:Scripts'")
For Each objFolder in colFolders
errResults = objFolder.Copy("D:Archive")
Wscript.Echo errResults
Next

——————————-
Copying Folders Using the Shell Folder Object
Const FOF_CREATEPROGRESSDLG = &H0&
ParentFolder = "D:Archive"
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(ParentFolder)
objFolder.CopyHere "C:Scripts", FOF_CREATEPROGRESSDLG
———————————–

Moving Folders Using the Shell Folder Object

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

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colFolders = objWMIService.ExecQuery _
("SELECT * FROM Win32_Directory WHERE Name = 'c:Scripts'")
For Each objFolder in colFolders
errResults = objFolder.Delete
Wscript.Echo errResults
Next

—————————————-
Compressing Folders

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colFolders = objWMIService.ExecQuery _
("SELECT * FROM Win32_Directory WHERE Name = 'c:Scripts'")
For Each objFolder in colFolders
errResults = objFolder.Compress
Wscript.Echo errResults
Next

——————————-
Uncompressing Folders

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colFolders = objWMIService.ExecQuery _
("SELECT * FROM Win32_Directory WHERE Name = 'c:Scripts'")
For Each objFolder in colFolders
errResults = objFolder.Uncompress
Wscript.Echo errResults
Next

——————————–
Retrieving Extended File Properties

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

————————————-
Enumerating All the Files on a Computer

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colFiles = objWMIService.ExecQuery _
("SELECT * FROM CIM_Datafile")
For Each objFile in colFiles
Wscript.Echo objFile.Name
Next

————————————-
Using an Asynchronous Query to Enumerate All the Files on a Computer

Const POPUP_DURATION = 120
Const OK_BUTTON = 0
Set objWSHShell = Wscript.CreateObject("Wscript.Shell")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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

—————————————–
Enumerating All the Files in a Folder

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colFiles = objWMIService.ExecQuery _
("SELECT * FROM CIM_DataFile WHERE Path = 'Scripts'")
For Each objFile in colFiles
Wscript.Echo objFile.Name
Next

————————————-
Enumerating a Specific Set of Files

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colFiles = objWMIService.ExecQuery _
("SELECT * FROM CIM_DataFile WHERE FileSize > 1000000")
For Each objFile in colFiles
Wscript.Echo objFile.Name & " – " & objFile.FileSize
Next
———————————–
Renaming Files

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colFiles = objWMIService.ExecQuery _
("SELECT * FROM Cim_Datafile WHERE Name = " _
& "'c:scriptstoggle_service.vbs'")
For Each objFile in colFiles
errResult = objFile.Rename("c:scriptstoggle_service.old")
Wscript.Echo errResult
Next

—————————————
Changing File Name Extensions

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

———————————
Copying Files

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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)
Next

——————————–
Deleting Files

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colFiles = objWMIService.ExecQuery _
("SELECT * FROM CIM_DataFile WHERE Extension = 'wma'")
For Each objFile in colFiles
objFile.Delete
Next

————————————-
Performing Actions on Files

TargetFolder = "C:Logs"
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(TargetFolder)
Set colItems = objFolder.Items
For Each objItem in colItems
objItem.InvokeVerbEx("Print")
Next

————————————-
Identifying Shell Object Verbs

Const RECYCLE_BIN = &Ha&
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(RECYCLE_BIN)
Set objFolderItem = objFolder.Self
Set colVerbs = objFolderItem.Verbs
For Each objVerb in colVerbs
Wscript.Echo objVerb
Next

————————————–
Monitoring File Creation

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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

—————————
Monitoring File Deletion

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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

—————————–
Monitoring File Modification
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM __InstanceModificationEvent WITHIN 10 WHERE " _
& "TargetInstance ISA 'CIM_DataFile' AND " _
& "TargetInstance.Name='c:scriptsindex.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

——————————
Enumerating Shared Folders

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colShares = objWMIService.ExecQuery("SELECT * FROM Win32_Share")
For Each objShare in colShares
Wscript.Echo "Allow Maximum: " & vbTab & objShare.AllowMaximum
Wscript.Echo "Caption: " & vbTab & objShare.Caption
Wscript.Echo "Maximum Allowed: " & vbTab & objShare.MaximumAllowed
Wscript.Echo "Name: " & vbTab & objShare.Name
Wscript.Echo "Path: " & vbTab & objShare.Path
Wscript.Echo "Type: " & vbTab & objShare.Type
Next

——————————
Creating Shared Folders

Const FILE_SHARE = 0
Const MAXIMUM_CONNECTIONS = 25
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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

—————————-
Mapping a Shared Folder to a Local Folder

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colShares = objWMIService.ExecQuery _
("ASSOCIATORS OF {Win32_Share.Name='Scripts'} WHERE " _
& "AssocClass=Win32_ShareToDirectory")
For Each objFolder in colShares
Wscript.Echo objFolder.Name
Next

—————————–
Deleting Network Shares

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colShares = objWMIService.ExecQuery _
("SELECT * FROM Win32_Share WHERE Name = 'FinanceShare'")
For Each objShare in colShares
objShare.Delete
Next

——————————-
Modifying Network Share Properties

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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.")
Next
Wscript.Echo errReturn

———————————

Publishing a Shared Folder in Active Directory

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

————————————–
Enumerating Published Shared Folders

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=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

—————————-
Searching for a Shared Folder in Active Directory

On Error Resume Next
Const ADS_SCOPE_SUBTREE = 2
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCOmmand.ActiveConnection = objConnection
objCommand.CommandText = "SELECT Name, unCName, ManagedBy FROM " _
& "'LDAP://DC=fabrikam,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

———————————–
Deleting a Published Folder in Active Directory

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

———————————-
Retrieving the Properties of Multiple Event Logs

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

————————————
Configuring Event Log Properties

Const wbemFlagUseAmendedQualifiers = &h20000
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & _
"{impersonationLevel=impersonate,(Security)}!" & _
strComputer & "rootcimv2")
Set colNTEventLogFiles = objWMIService.ExecQuery _
("SELECT * FROM Win32_NTEventLogFile")
For each objNTEventLogFile in colNTEventLogFiles
objNTEventLogFile.MaxFileSize = 4194304
objNTEventLogFile.OverwriteOutDated = 14
objNTEventLogFile.Put_ wbemFlagUseAmendedQualifiers
Next

————————————
Backing Up and Clearing an Event Log

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate,(Backup)}!" & _
strComputer & "rootcimv2")
Set colLogFiles = objWMIService.ExecQuery _
("SELECT * FROM Win32_NTEventLogFile WHERE LogFileName='Application'")
For Each objLogfile in colLogFiles
errBackupLog = objLogFile.BackupEventLog("c:scriptsapplication.evt")
If errBackupLog <> 0 Then
Wscript.Echo "The Application event log could not be backed up."
Else
objLogFile.ClearEventLog()
End If
Next

————————————-
Backing Up and Clearing Event Logs If the Log Meets Specific Conditions

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate, (Backup, Security)}!" _
& strComputer & "rootcimv2")
Set colLogFiles = objWMIService.ExecQuery _
("SELECT * FROM Win32_NTEventLogFile")
For Each objLogfile in colLogFiles
If objLogFile.FileSize > 20000000 Then
strBackupLog = objLogFile.BackupEventLog _
("c:scripts" & objLogFile.LogFileName & ".evt")
objLogFile.ClearEventLog()
End If
Next

————————————
Creating Unique File Names When Backing Up Event Logs

dtmThisDay = Day(Now)
dtmThisMonth = Month(Now)
dtmThisYear = Year(Now)
strBackupName = dtmThisYear & "_" & dtmThisMonth & "_" & dtmThisDay
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate,(Backup)}!" & _
strComputer & "rootcimv2")
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()
Next

—————————————
Querying a Specific Event Log

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colLoggedEvents = objWMIService.ExecQuery _
("SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'System'")
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
Next

—————————————
Querying an Event Log for a Specific Event ID

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colLoggedEvents = objWMIService.ExecQuery _
("SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'System' AND " _
& "EventCode = '6008'")
Wscript.Echo "Improper shutdowns: " & colLoggedEvents.Count

——————————————————
Querying an Event Log for All Events From a Specified Day

dtmStartDate = "20021219000000.000000-480"
dtmEndDate = "20021220000000.000000-480"
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

—————————————
Asynchronously Querying an Event Log

Const POPUP_DURATION = 10
Const OK_BUTTON = 0
Set objWSHShell = Wscript.CreateObject("Wscript.Shell")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set objSink = WScript.CreateObject("WbemScripting.SWbemSink","SINK_")
objWMIService.InstancesOfAsync objSink, "Win32_NTLogEvent"
errReturn = objWshShell.Popup("Retrieving events", 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

—————————————-
Copying Events to a Database

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 & "rootcimv2")
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

———————————–
Writing an Event to the Application Log

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

————————————–
Writing an Event to the Application Log on a Remote Computer

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

—————————————-
Adding WMI Data to an Event Log Entry

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

——————————————-
Creating a Custom Event Log

Const NO_VALUE = Empty
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.RegWrite _
"HKLMSystemCurrentControlSetServicesEventLogScriptingEventLog", _
NO_VALUE

———————————————
Parsing a Comma-Separated-Values Log

Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("C:WindowsSystem32DHCP" _
& "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
objTextFile.Close
———————————–
Parsing a Fixed-Width-Column Log

Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("C:WindowsDebugNetsetup.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
objTextFile.Close

————————————

Monitoring the Status of All the Printers on a Computer

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

——————————————-
Displaying Printer Status in a Web Page

<SCRIPT LANGUAGE = "VBScript">
Sub window_onLoad
GetInfo
iTimerID = window.setInterval("GetInfo", 60000, "VBScript")
End Sub
Sub GetInfo
For i = (objTable.Rows.Length – 1) to 0 Step -1
myNewRow = Document.All.objTable.deleteRow(i)
Next
Set objRow = objTableBody.InsertRow()
objRow.Style.fontWeight = "bold"
Set objCell = objRow.InsertCell()
objCell.InnerText = "Name"
Set objCell = objRow.InsertCell()
objCell.InnerText = "Location"
Set objCell = objRow.InsertCell()
objCell.InnerText = "Status"
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & _
strComputer & "rootcimv2")
Set colPrinters = objWMIService.ExecQuery _
("SELECT * FROM Win32_Printer")
For Each objPrinter in colPrinters
Set objRow = objTableBody.InsertRow()
Set objCell = objRow.InsertCell()
objCell.InnerText = objPrinter.Name
Set objCell = objRow.InsertCell()
objCell.InnerText = objPrinter.Location
Set objCell = objRow.InsertCell()
Select Case objPrinter.PrinterStatus
Case 1
strPrinterStatus = "Other"
Case 2
strPrinterStatus = "Unknown"
Case 3
strPrinterStatus = "Idle"
Case 4
strPrinterStatus = "Printing"
Case 5
strPrinterStatus = "Warming up"
End Select
objCell.InnerText = strPrinterStatus
Next
End Sub
</SCRIPT>
<TABLE ID = "objTable" border = "1" >
<TBODY ID = "objTableBody">
</TBODY>
</TABLE>

—————————————–
Receiving Notification When a Printer Stops

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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."
Next
End If

——————————-
Monitoring Printer Status Using a Temporary Event Subscription

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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

————————————
Verifying the Status of the Print Service

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colRunningServices = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service WHERE Name = 'Spooler'")
For Each objService in colRunningServices
Wscript.Echo objService.DisplayName & ": " & objService.State
Next

—————————————–
Reporting Print Queue Statistics

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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

—————————————–
Monitoring Print Job Status

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

————————————–
Monitoring the Time Print Jobs Spend in a Print Queue

Set objPrinter = GetObject("WinNT://atl-ps-01/ArtDepartmentPrinter")
Set colPrintJobs = objPrinter.PrintJobs
For Each objPrintJob in colPrintJobs
dtmTimeInQueue = DateDiff("n", objPrintJob.TimeSubmitted, Now)
If dtmTimeInQueue > 15 Then
Wscript.Echo objPrintJob.Description, dtmTimeInQueue
End If
Next

——————————————-
Enumerating Printers and Printer Capabilities

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

—————————————
Pausing a Single Printer

Set objPrinter = GetObject("WinNT://atl-ps-01/ArtDepartmentPrinter")
objPrinter.Pause

————————————–
Resuming a Printer

Set objPrinter = GetObject("WinNT://atl-ps-01/ArtDepartmentPrinter")
objPrinter.Resume

————————————-
Purging a Print Queue

Set objPrinter = GetObject("WinNT://atl-ps-01/ArtDepartmentPrinter")
objPrinter.Purge

————————————
Pausing Print Jobs

Set objPrinter = GetObject("WinNT://atl-ps-01/ArtDepartmentPrinter")
Set colPrintJobs = objPrinter.PrintJobs
For Each objPrintJob in colPrintJobs
If objPrintJob.Size > 400000 Then
objPrintJob.Pause
End If
Next

————————————–
Resuming Print Jobs

Set objPrinter = GetObject("WinNT://atl-ps-01/ArtDepartmentPrinter")
Set colPrintJobs = objPrinter.PrintJobs
For Each objPrintJob in colPrintJobs
objPrintJob.Resume
Next

————————————–
Adding a Printer Connection

Set objNetwork = CreateObject("Wscript.Network")
objNetwork.AddWindowsPrinterConnection "atl-ps-01Xerox300"
objNetwork.SetDefaultPrinter "atl-ps-01Xerox300"

—————————————-
Removing a Printer Connection
Set objNetwork = CreateObject("Wscript.Network")
objNetwork.RemovePrinterConnection "atl-ps-01xerox3006"

————————————————
Enumerating All the Published Printers in Active Directory

On Error Resume Next
Const ADS_SCOPE_SUBTREE = 2
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection
objCommand.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

———————————————-
Searching for Specific Printers in Active Directory

On Error Resume Next
Const ADS_SCOPE_SUBTREE = 2
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCOmmand.ActiveConnection = objConnection
objCommand.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

———————————–
Monitoring Process Availability

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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

————————————
Monitoring Process Creation

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colMonitoredProcesses = objWMIService. _
ExecNotificationQuery("SELECT * FROM __InstanceCreationEvent " _
& "WITHIN 10 WHERE TargetInstance ISA 'Win32_Process'")
i = 0
Do While i = 0
Set objLatestProcess = colMonitoredProcesses.NextEvent
Wscript.Echo objLatestProcess.TargetInstance.Name, Now
Loop

———————————-
Monitoring Process Deletion

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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, Now
Loop

————————————

Monitoring Process Performance

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

———————————-
Monitoring Process Performance Over Time

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
For i = 1 to 10
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
Next
Wscript.Echo
Wscript.Sleep 60000
Next

————————————
Monitoring Processor Use by Process

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

————————————-
Displaying Process Performance on a Web Page

<SCRIPT LANGUAGE = "VBScript">
Sub window_onLoad
iTimerID = window.setInterval("GetInfo", 10000, "VBScript")
End Sub
Sub GetInfo
For i = (objTable.Rows.Length – 1) to 0 Step -1
myNewRow = document.all.objTable.deleteRow(i)
Next
Set objRow = objTableBody.InsertRow()
objRow.Style.fontWeight = "bold"
Set objCell = objRow.InsertCell()
objCell.InnerText = "Process ID"
Set objCell = objRow.InsertCell()
objCell.InnerText = "Process Name"
Set objCell = objRow.InsertCell()
objCell.InnerText = "Working Set Size"
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colProcesses = objWMIService.ExecQuery _
("SELECT * FROM Win32_Process")
For Each strProcess in colProcesses
Set objRow = objTableBody.InsertRow()
Set objCell = objRow.InsertCell()
objCell.InnerText = strProcess.ProcessID
Set objCell = objRow.InsertCell()
objCell.InnerText = strProcess.Name
Set objCell = objRow.InsertCell()
objCell.InnerText = FormatNumber(strProcess.WorkingSetSize,0,,,-1)
Next
End Sub
</SCRIPT>
<TABLE ID = "objTable">
<TBODY ID = "objTableBody">
</TBODY>
</TABLE>

—————————————
Determining Process Ownership
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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 & "."
Next

———————————-

Monitoring Threads

Set objDictionary = CreateObject("Scripting.Dictionary")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

———————————
Creating a Process on a Remote Computer

strComputer = "webserver"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & _
"rootcimv2:Win32_Process")
errReturn = objWMIService.Create("database.exe", null, null, intProcessID)
If errReturn = 0 Then
Wscript.Echo "Database.exe was started with a process ID of " _
& intProcessID & "."
Else
Wscript.Echo "Database.exe could not be started due to error " & _
errReturn & "."
End If

———————————————
Creating a Process in a Hidden Window

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

——————————————–
Creating a Higher-Priority Process

Const ABOVE_NORMAL = 32768
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set objStartup = objWMIService.Get("Win32_ProcessStartup")
Set objConfig = objStartup.SpawnInstance_
objConfig.PriorityClass = ABOVE_NORMAL
Set objProcess = GetObject("winmgmts:rootcimv2:Win32_Process")
objProcess.Create "Database.exe", Null, objConfig, intProcessID
———————————————-
Terminating a Process

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colProcessList = objWMIService.ExecQuery _
("SELECT * FROM Win32_Process WHERE Name = 'Diagnose.exe'")
For Each objProcess in colProcessList
objProcess.Terminate()
Next

——————————————–
Preventing a Process from Running

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colMonitoredProcesses = objWMIService. _
ExecNotificationQuery("SELECT * FROM __InstanceCreationEvent " _
& " WITHIN 1 WHERE TargetInstance IS 'Win32_Process'")
i = 0
Do While i = 0
Set objLatestProcess = colMonitoredProcesses.NextEvent
If objLatestProcess.TargetInstance.Name = "Download.exe" Then
objLatestProcess.TargetInstance.Terminate()
End If
Loop

——————————————
Monitoring Service Availability

strComputer = "."
Set objWMIService = GetObject("winmgmts:" & _
"{impersonationLevel=Impersonate}!" & strComputer & "rootcimv2")
Set colServices = objWMIService.ExecQuery("SELECT * FROM Win32_Service")
For Each objService in colServices
Wscript.Echo objService.DisplayName & " = " & objService.State
Next
————————————–
Monitoring Inactive Services

strComputer = "."
Set objWMIService = GetObject("winmgmts:" & _
"{impersonationLevel=Impersonate}!" & strComputer & "rootcimv2")
Set colStoppedServices = objWMIService.ExecQuery _
("SELECT DisplayName,State FROM Win32_Service WHERE State <> 'Running'")
For Each objService in colStoppedServices
Wscript.Echo objService.DisplayName & " = " & objService.State
Next

————————————-
Monitoring Changes in Service Status by Using a Temporary Event Subscriber

strComputer = "."
Set objWmiService = GetObject("winmgmts:" & _
"{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set objWmiEventSource = objWMIService.ExecNotificationQuery _
("SELECT * FROM __InstanceModificationEvent " & _
"WITHIN 30 WHERE TargetInstance ISA 'Win32_Service'")
Do
Set objService = objWmiEventSource.NextEvent
If objService.TargetInstance.State <> _
objService.PreviousInstance.State Then
Wscript.Echo objService.TargetInstance.DisplayName & _
" is " & objService.TargetInstance.State & _
". The service previously was " & _
objService.PreviousInstance.State & "."
End If
Loop

————————————-
Retrieving Service Properties

Const ForAppending = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLogFile = objFSO.OpenTextFile("c:scriptsservice_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 & "rootcimv2")
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
Next
objLogFile.Close
———————————————
Displaying the Services Running in a Specified Process

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colListOfServices = objWMIService.ExecQuery("SELECT * FROM Win32_Service")
For Each objService in colListOfServices
If objService.PathName = "c:windowssystem32services.exe" Then
Wscript.Echo objService.DisplayName
End If
Next

————————————–
Displaying the Services Running in All Processes on a Computer

set objIdDictionary = CreateObject("Scripting.Dictionary")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

————————————
Determining Which Services Can Be Stopped

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colServices = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service WHERE AcceptStop = True")
For Each objService in colServices
Wscript.Echo objService.DisplayName
Next

————————————–
Determining Which Services Can Be Paused

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colServices = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service WHERE AcceptPause = True")
For Each objService in colServices
Wscript.Echo objService.DisplayName
Next

—————————————
Stopping Services Running Under a Specified Account

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colServices = objWMIService.ExecQuery _
("SELECT * FROM win32_Service WHERE StartName = '.Netsvc'")
For Each objService in colServices
errReturnCode = objService.StopService()
Next

———————————————
Pausing Services Running Under a Specified Account

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colProcesses = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service WHERE StartName = '.Netsvc'")
For Each objService in colServices
errReturnCode = objService.PauseService()
Next

————————————————–

Starting Automatic Services That Are Stopped

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colListOfServices = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service WHERE State = 'Stopped' and StartMode = " _
& "'Auto'")
For Each objService in colListOfServices
objService.StartService()
Next

————————————————

Resuming Automatic Services That Are Paused

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colListOfServices = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service WHERE State = 'Paused' and StartMode = " _
& "'Auto'")
For Each objService in colListOfServices
objService.ResumeService()
Next

—————————————————-
Enumerating Dependent Services for a Single Service

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

————————————————
Enumerating Dependent Services for All the Services on a Computer

Const ForAppending = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLogFile = _
objFSO.OpenTextFile("c:scriptsservice_dependencies.csv", _
ForAppending, True)
objLogFile.Write("Service Dependencies")
objLogFile.Writeline
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colListOfServiceS = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service")
For Each objService in colListofServices
objServiceRegistryName = objService.Name
objServiceDisplayName = objService.DisplayName
Set colServiceList = GetObject("winmgmts:").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)
objLogFile.Writeline
Next
End If
Next
objLogFile.Close

—————————————-
Enumerating Antecedent Services

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colServiceList = objWMIService.ExecQuery _
("ASSOCIATORS OF {Win32_Service.Name='fax'} WHERE " _
& "AssocClass=Win32_DependentService Role=Dependent" )
For Each objService in colServiceList
Wscript.Echo objService.DisplayName
Next

—————————————-
Stopping a Service and Its Dependents

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colServiceList = objWMIService.ExecQuery _
("ASSOCIATORS OF {Win32_Service.Name='iisadmin'} WHERE " _
& "AssocClass=Win32_DependentService Role=Antecedent" )
For Each objService in colServiceList
errReturn = objService.StopService()
Next
Wscript.Sleep 60000
Set colServiceList = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service WHERE Name='iisadmin'")
For Each objService in colServiceList
errReturn = objService.StopService()
Next

———————————–
Starting Dependent Services

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colServiceList = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service WHERE Name='iisadmin'")
For Each objService in colServiceList
errReturn = objService.StartService()
Next
Wscript.Sleep 60000
Set colServiceList = objWMIService.ExecQuery _
("ASSOCIATORS OF {Win32_Service.Name='iisadmin'} WHERE " _
& "AssocClass=Win32_DependentService Role=Antecedent" )
For Each objService in colServiceList
objService.StartService()
Next

———————————-
Configuring Service Start Options

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

————————————
Configuring Service Error Control Codes

Const NORMAL = 1
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colServiceList = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service WHERE ErrorControl = 'Ignore'")
For Each objService in colServiceList
errReturn = objService.Change( , , , NORMAL)
Next

——————————————
Switching Service Accounts to LocalSystem

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colServiceList = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service WHERE StartName = '.NetSvc'")
For Each objService in colServices
errServiceChange = objService.Change _
( , , , , , , ".LocalSystem" , "")
Next

—————————————–
Changing a Service Account Password

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colServiceList = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service WHERE StartName = '.NetSvc'")
For Each objservice in colServiceList
errReturn = objService.Change( , , , , , , , "password")
Next

—————————————–

Installing a Service

Const OWN_PROCESS = 16
Const NOT_INTERACTIVE = True
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set objService = objWMIService.Get("Win32_BaseService")
errReturn = objService.Create ("DbService", "Personnel Database", _
"c:windowssystem32db.exe", OWN_PROCESS ,2 ,"Automatic" , _
NOT_INTERACTIVE ,".LocalSystem" ,"")

—————————-
removing a service

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colListOfServices = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service WHERE Name = 'DbService'")
For Each objService in colListOfServices
objService.StopService()
objService.Delete()
Next

—————————————–
Listing the Files That Make Up the Registry

Const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."

Set objReg=GetObject("winmgmts:{impersonationLevel=impersonate}!" & _
strComputer & "rootdefault:StdRegProv")
strKeyPath = "SystemCurrentControlSetControlhivelist"
objReg.EnumValues HKEY_LOCAL_MACHINE, strKeyPath, _
arrValueNames, arrValueTypes

For i=0 To UBound(arrValueNames)
Wscript.Echo "File Name: " & arrValueNames(i)
objReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath, _
arrValueNames(i),strValue
Wscript.Echo "Location: " & strValue
Next

—————————————–
Backing Up the Registry

Set objShell = CreateObject("WScript.Shell")
objShell.Exec "%comspec% /k reg.exe SAVE HKLM/System sw.hiv"

————————————
Retrieving Arguments from a Text File

Const ForReading = 1
Set objDictionary = CreateObject("Scripting.Dictionary")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
("c:scriptsservers.txt", ForReading)
i = 0
Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.Readline
objDictionary.Add i, strNextLine
i = i + 1
Loop
For Each objItem in objDictionary
StrComputer = objDictionary.Item(objItem)
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer& "rootcimv2")
Set colServices = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service")
Wscript.Echo strComputer, colServices.Count
Next

———————————————-
Using a Text File as a Command-Line Argument

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
StrComputer = objDictionary.Item(objItem)
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer& "rootcimv2")
Set colServices = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service")
Wscript.Echo strComputer, colServices.Count
Next

———————————————-
Retrieving Arguments from a Database

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 ServerList" , objConnection, _
adOpenStatic, adLockOptimistic
objRecordSet.MoveFirst
Do While Not objRecordSet.EOF
strComputer = objRecordSet("ComputerName")
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer& "rootcimv2")
Set colServices = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service")
Wscript.Echo strComputer, colServices.Count
objRecordSet.MoveNext
Loop
objRecordset.Close
objConnection.Close

—————————————
Retrieving Arguments from an Active Directory Container

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
StrComputer = objDictionary.Item(objItem)
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer& "rootcimv2")
Set colServices = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service")
Wscript.Echo strComputer, colServices.Count
Next

————————————–
Displaying Tabular Output in a Command Window

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer& "rootcimv2")
Set colServices = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service")
For Each objService in colServices
intPadding = 50 – Len(objService.DisplayName)
intPadding2 = 17 – Len(objService.StartMode)
strDisplayName = objService.DisplayName & Space(intPadding)
strStartMode = objService.StartMode & Space(intPadding2)
Wscript.Echo strDisplayName & strStartMode & objService.State
Next

—————————————–
Displaying Data in a Web Page

Set objExplorer = CreateObject("InternetExplorer.Application")
objExplorer.Navigate "about:blank"
objExplorer.ToolBar = 0
objExplorer.StatusBar = 0
objExplorer.Width = 800
objExplorer.Height = 570
objExplorer.Left = 0
objExplorer.Top = 0
objExplorer.Visible = 1

Do While (objExplorer.Busy)
Loop

Set objDocument = objExplorer.Document
objDocument.Open

objDocument.Writeln "<html><head><title>Service Status</title></head>"
objDocument.Writeln "<body bgcolor='white'>"
objDocument.Writeln "<table width='100%'>"
objDocument.Writeln "<tr>"
objDocument.Writeln "<td width='50%'><b>Service</b></td>"
objDocument.Writeln "<td width='50%'><b>State</b></td>"
objDocument.Writeln "</tr>"

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer& "rootcimv2")
Set colServices = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service")

For Each objService in colServices
objDocument.Writeln "<tr>"
objDocument.Writeln "<td width='50%'>" & objService.DisplayName & "</td>"
objDocument.writeln "<td width='50%'>" & objService.State & "</td>"
objDocument.Writeln "</tr>"
Next

objDocument.Writeln "</table>"
objDocument.Writeln "</body></html>"
objDocument.Write()
objDocument.Close

———————————-
Stopping a Script When Internet Explorer Closes

Set objExplorer = WScript.CreateObject _
("InternetExplorer.Application", "IE_")
objExplorer.Navigate "about:blank"
objExplorer.ToolBar = 0
objExplorer.StatusBar = 0
objExplorer.Width = 400
objExplorer.Height = 250
objExplorer.Left = 0
objExplorer.Top = 0
objExplorer.Visible = 1
Set objDocument = objExplorer.Document
objDocument.Open
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer& "rootcimv2")
Set colServices = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service")
For Each objService in colServices
objDocument.Writeln objService.DisplayName & "<BR>"
Wscript.Sleep 2000
Next
Sub IE_onQuit()
Wscript.Quit
End Sub

————————————
Using an HTA to Display Service Information

<HTML>
<HEAD>
<HTA:Application
Border = Thick
BorderStyle = Complex
ShowInTaskBar = No
MaximizeButton = No
MinimizeButton = No
>
<SCRIPT LANGUAGE="VBScript">
Sub window_onLoad
Set objDocument = self.Document
objDocument.open
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colServices = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service")
For Each objService in colServices
objdocument.WriteLn objService.DisplayName & "<br>"
Next
End Sub
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>

——————————-
Displaying Data by Using the Tabular Data Control

<HTML>
<BODY>
<OBJECT id="serviceList" CLASSID="clsid:333C7BC4-460F-11D0-BC04-0080C7055A83">
<PARAM NAME="DataURL" VALUE="c:scriptsservice_list.csv">
<PARAM NAME="UseHeader" VALUE="True">
<PARAM NAME="TextQualifier" VALUE=",">
</OBJECT>
<H2>Current Service Status</H2>
<table border='1' width='100%' cellspacing='0' datasrc=#serviceList>
<THEAD><TR>
<TD>Computer</TD>
<TD>Service</TD>
<TD>Status</TD>
</TR>
</THEAD>
<TBODY>
<TR>
<TD><B><DIV datafld="System Name"></DIV></B></TD>
<TD><DIV datafld="Display Name"></DIV></TD>
<TD><DIV datafld="Service State"></DIV></TD>
</TR>
</TBODY>
</TABLE>
</BODY>
</HTML>
—————————–

Displaying Sorted Data by Using the Tabular Data Control

<HTML>
<BODY>
<OBJECT id="serviceList" CLASSID="clsid:333C7BC4-460F-11D0-BC04-0080C7055A83">
<PARAM NAME="DataURL" VALUE="c:scriptsservice_list.csv"> <PARAM
NAME="UseHeader" VALUE="True">
<PARAM NAME="TextQualifier" VALUE=",">
<PARAM NAME="SortColumn" VALUE="Service State">
</OBJECT>
<H2>Current Service Status</H2>
<table border='1' width='100%' cellspacing='0' datasrc=#serviceList>
<THEAD><TR>
<TD>Computer</TD>
<TD>Service</TD>
<TD>Status</TD>
</TR>
</THEAD>
<TBODY>
<TR>
<TD><B><DIV datafld="System Name"></DIV></B></TD>
<TD><DIV datafld="Display Name"></DIV></TD>
<TD><DIV datafld="Service State"></DIV></TD>
</TR>
</TBODY>
</TABLE>
</BODY>
</HTML>

————————————–
Connecting to an ADO Database

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

———————————–
Adding New Records to a Database

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
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer& "rootcimv2")
Set colSoundCards = objWMIService.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

————————————
Finding Records in a Recordset

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

———————————
Updating Records in a Database

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
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer& "rootcimv2")
Set colSoundCards = objWMIService.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

—————————————-
Deleting Selected Records from a Database

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

—————————————-
Deleting All Records in a Database Table

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

————————————–
Masking Passwords by Using Internet Explorer

Microsoft® Windows® 2000 Scripting Guide

You can use Internet Explorer as a way to enter passwords. To mask passwords using Internet Explorer, you need to:

1.
Create a Web page to use as the form. The Web page must contain, at a minimum:

• A password box for entering the password.

• An OK button, to be clicked after a password has been entered.

• A hidden text field. When the OK button is clicked, the value of the hidden text field is changed. The script used to open the Web page monitors this text field for changes. Because the value will change only when the OK button is clicked, the script will pause until this change is detected.

• For example, the HTML coding might look like this:

<SCRIPT language="VBScript">
<!–
Sub OKButton_OnClick
OkClicked.Value = 1
End Sub
'–>
</SCRIPT>
<BODY>
Please enter your password: <INPUT TYPE=password Name = "PasswordBox" size="20">
<P>
<INPUT NAME="OKButton" TYPE="BUTTON" VALUE="OK" >
<P>
<input type="hidden" name="OKClicked" size="20">
</BODY>

2.
Create a script that opens the Web page and waits for the password to be entered.

3.
Provide a mechanism for the script to identify the password that was typed in the password box.

Scripting Steps
Listing 17.21 contains a script that masks passwords entered in Internet Explorer. (To actually use the script, you will have to create the file C:ScriptsPassword.asp.) To carry out this task, the script must perform the following steps:

1.
Use the Wscript CreateObject method to create an instance of Internet Explorer, and assign the name IE_ to the event handler responsible for monitoring Internet Explorer events.

2.
Use the Navigate method to open the Web page C:ScriptsPassword.asp.

3.
Configure various Internet Explorer properties, such as width and height, and hide items such as the toolbar and the status bar.

4.
Set the Visible property to 1 to display Internet Explorer, opened to the correct page and properly configured.

5.
Use a Do loop to pause the script until the OK button in Internet Explorer has been clicked.

This is done by periodically checking the value of a hidden text field named OKClicked. If this text box is empty, the script sleeps for 250 milliseconds and then checks again. When the OK button is clicked, the value of this text box is set to 1. At that point, the script exits the loop.

6.
Set the value of the variable strPassword to the value of the PasswordBox text box. This is the name of the text box in Internet Explorer where the user typed the password.

7.
Use the Quit method to close Internet Explorer.

8.
Pause for 250 milliseconds.

9.
Echo the value of strPassword. In a production script, you would probably not echo the value of strPassword but instead would use it to connect to a resource of some kind.

Listing 17.21 Masking Passwords in Internet Explorer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Set objExplorer = WScript.CreateObject _
("InternetExplorer.Application", "IE_")
objExplorer.Navigate "file:///c:scriptspassword.asp"
objExplorer.ToolBar = 0
objExplorer.StatusBar = 0
objExplorer.Width = 400
objExplorer.Height = 250
objExplorer.Left = 0
objExplorer.Top = 0
objExplorer.Visible = 1
Do While (objExplorer.Document.All.OKClicked.Value = "")
Wscript.Sleep 250
Loop
strPassword = objExplorer.Document.All.PasswordBox.Value
objExplorer.Quit
Wscript.Sleep 250
Wscript.Echo strPassword

The script shown in Listing 17.22 shows how a masked password can be retrieved from Internet Explorer, and then used to connect to a remote computer and install a software package. In line 10, the variable strPassword, which contains the value typed by the user, is used to connect to the remote computer. This is done rather than hard-coding the password in the script.

Listing 17.22 Using a Password Masked in Internet Explorer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

Const wbemImpersonationLevelDelegate = 4

Set objExplorer = WScript.CreateObject _
("InternetExplorer.Application", "IE_")
objExplorer.Navigate "file:///c:scriptspassword.asp"
objExplorer.ToolBar = 0
objExplorer.StatusBar = 0
objExplorer.Width = 400
objExplorer.Height = 250
objExplorer.Left = 0
objExplorer.Top = 0
objExplorer.Visible = 1
Do While (objExplorer.Document.All.OKClicked.Value = "")
Wscript.Sleep 250
Loop
strPassword = objExplorer.Document.All.PasswordBox.Value
objExplorer.Quit

Set objWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objConnection = objwbemLocator.ConnectServer _
("WebServer", "rootcimv2", "fabrikamadministrator", _
strPassword")
Set objSoftware = objConnection.Get("Win32_Product")
errReturn = objSoftware.Install("atl-dc-02scripts1561_lab.msi",,True)

—————————————

Sending E-Mail from a Script

Microsoft® Windows® 2000 Scripting Guide

Enabling a script to send automated e-mail messages provides a way for your script to send real-time alerts whenever a particular event occurs (for example, when the script runs, when the script finishes, or when the script encounters a problem of some kind). Alerts are commonly used in system administration scripting, but these notices are typically displayed either by using pop-up message boxes or by recording an event in the event log. Although both of these techniques are useful, they require someone to either physically sit at the computer where the message box is displayed or continually monitor the event log for the occurrence of new events.

By contrast, e-mail alerts can be directed to a particular administrator or group of administrators regardless of their physical location; administrators can receive these alerts even if they are off-site. Because most administrators read their e-mail more often than they read event logs, there is a greater chance that they will respond quickly to the e-mail alert. With the new generation of PDAs and cell phones that can be used to check e-mail, the ability to programmatically send alerts using this technology becomes even more valuable.

E-mail can be sent from any Microsoft® Windows® 2000-based computer by using CDO.

Scripting Steps
Listing 17.23 contains a script that sends an e-mail message by using CDO. To carry out this task, the script must perform the following steps:

1.
Create an instance of a CDO e-mail message.

2.
Set the values for the From, To, Subject, and TextBody properties of the message.

3.
Use the Send method to send the message.

For this script to work, the SMTP service must be installed on the computer where the script is being run.

Listing 17.23 Sending E-Mail from a Script

1
2
3
4
5
6

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

—————————————–
Sending E-Mail Without Installing the SMTP Service

Microsoft® Windows® 2000 Scripting Guide

The script shown in Listing 17.23 can be used as long as the SMTP service is installed on the computer where the script is running. Obviously, this poses a problem: Most likely, you do not want the SMTP service to be installed and running on every one of your computers.

Even if the SMTP service is not installed on the computer, you can still send e-mail from a script as long as the SMTP service is installed somewhere on your network. To do this, your script must include code that specifies the properties of the computer and the SMTP service that will be used to send the message.

Each e-mail Message object has an associated Configuration object that defines configuration settings for sending the message. These settings are stored as fields within the Configuration object; each field is a Uniform Resource Identifier (URI) that contains information for the configuration setting. The three URIs required to send an SMTP e-mail message are shown in Table 17.10.

Table 17.10 Required URIs for Sending SMTP E-Mail Messages

Configuration Field Description
SendUsing
Indicates how the message is to be sent. Values are:

1 – Send messages by using the locally installed SMTP service. Use this value if the SMTP service is installed on the computer where the script is running.

2 – Send messages by using the SMTP service on the network. Use this value if the SMTP service is not installed on the computer where the script is running.

The full name for this field is:

http://schemas.Microsoft.com/cdo/configuration/sendusing

SmtpServer
DNS name or IP address of the SMTP server through which messages are sent.

The full name for this field is:

http://schemas.Microsoft.com/cdo/configuration/smtpserver

SmtpServerPort
The port on which the SMTP server listens for connections. This is typically port 25.

The full name for this field is:

http://schemas.Microsoft.com/cdo/configuration/smtpserverport

Scripting Steps
Listing 17.24 contains a script that sends e-mail from a computer that is not running the SMTP service. To carry out this task, the script must perform the following steps:

1.
Create an instance of a CDO e-mail message.

2.
Set the values for the From, To, Subject, and TextBody properties of the message.

3.
Specify the configuration properties for the remote SMTP server. In this script, those properties and their values are:

• SendUsing. This property is set to 2, meaning that the SMTP service is not installed on this computer. Messages must instead be sent by using the computer specified in the SMTPServer property.

• SMTPServer. This property is set to MySMTPHost, the name of the SMTP server on this hypothetical network. If the name of your SMTP server is MailServer1, set this property to MailServer1.

• SMTPServerPort. This property is set to 25, the default SMTP port for most computers.

4.
Use the Send method to send the message.

Listing 17.24 Sending E-Mail Without Installing the SMTP Service

1
2
3
4
5
6
7
8
9
10
11
12
13
14

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") = _
"MySMTPHost"
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objEmail.Configuration.Fields.Update
objEmail.Send

—————————————–
Tracking Script Progress by Using Internet Explorer

Microsoft® Windows® 2000 Scripting Guide

If you feel that a script needs a progress indicator, it is recommended that you use a graphical progress indicator; after all, if visual cues are important, your progress indicator should be visually compelling. Perhaps the easiest way to add a graphical progress indicator to your scripts is to use Internet Explorer.

By the way, this is true even if the script runs in a command window under CScript; Internet Explorer can be instantiated and used as a progress indicator even if the script is running from the command line.

One way to indicate progress by using Internet Explorer is to display a message in the browser. In some cases, you might want to display a single message ("Please wait….") and then have the message disappear when the script is finished. Alternatively, you might want to periodically change the message to reflect whatever the script is doing. For example, if you have a script that stopped a service, waited two minutes, and then restarted the service, you might display these messages in the browser:

• Stopping service….

• Waiting two minutes before restarting service….

• Restarting service….

Regardless of the number or the type of messages you choose to display, you can display custom messages within Internet Explorer by configuring the InnerHTML property of the document body. This replaces the entire document body with the specified text. For example, this code clears the document and displays the message, "Service retrieval in progress.":

objExplorer.Document.Body.InnerHTML = "Service retrieval in progress."

You can also use standard HTML tags to include formatting when setting the InnerHTML property. For example, this code uses the < B> tag to display the message in bold:

objExplorer.Document.Body.InnerHTML = "<B>Service information retrieved.</B>"

There are two important points to keep in mind when using Internet Explorer as a progress indicator:

• Closing Internet Explorer will not necessarily terminate the script. However, it is possible to code your script so that closing Internet Explorer will stop the script from running.

• If Internet Explorer is closed and your script attempts to manipulate the nonexistent object, an error will occur.

To prevent this, use On Error Resume Next statement within the script. Anytime you attempt to manipulate Internet Explorer, check the error number. If the error number is anything other than 0, that means a problem occurred, and it is likely that Internet Explorer is no longer available. In that case, you must decide whether you want your script to terminate itself, continue without a progress indicator, or generate a new instance of Internet Explorer.

For information about a way to overcome these problems, see "Stopping a Script When Internet Explorer Is Closed" in this chapter.

Scripting Steps
Listing 17.25 contains a script that tracks script progress by using Internet Explorer. To carry out this task, the script must perform the following steps:

1.
Create an instance of Internet Explorer.

2.
Open a blank Web page by navigating to "about:blank".

3.
Configure the user interface settings, and then show Internet Explorer by setting the Visible property to True.

4.
Set the InnerHTML property of the document to the message "Retrieving service information. This might take several minutes to complete."

5.
Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to "impersonate."

6.
Use the ExecQuery method to query the Win32_Service class.

This query returns a collection consisting of all the services installed on the computer.

7.
For each service in the collection, pause for 200 milliseconds. This is done simply to ensure that the progress indicator remains on the screen long enough for you to view it.

8.
Set the InnerHTML property of the document to the message "Service information retrieved."

9.
Pause for 3 seconds (3,000 milliseconds). This pause is inserted simply to give the user a chance to see the message that service information has been retrieved.

10.
Use the Quit method to dismiss Internet Explorer.

Listing 17.25 Tracking Script Progress by Using Internet Explorer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

Set objExplorer = 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 objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer& "rootcimv2")
Set colServices = objWMIService.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

————————————
Tracking Dynamic Script Progress by Using Internet Explorer

Microsoft® Windows® 2000 Scripting Guide

The script shown in Listing 17.26 displays a message when the script starts and then displays a second message when the script ends. To create a more dynamic progress bar, you might want to do something to indicate the intermediate steps taken by the script. This can be as simple as displaying an asterisk (*) inside the browser window each time a service is retrieved and acted upon.

To create a dynamic progress indicator, you can use the WriteLn method to write information to the browser each time the script takes a particular action. As a result, you end up with a progress indicator similar to the one shown in Figure 17.4. Each time a service is retrieved and acted upon, another asterisk is added to the browser window.

Figure 17.4 Tracking Dynamic Script Progress by Using Internet Explorer

See full-sized image.

Tip

• By using different fonts, you can create a progress indicator that uses solid bars or dots rather than asterisks. For example, the letter "n" in the Wingdings font looks like this: &nu;.

Scripting Steps
Listing 17.26 contains a script that tracks script progress dynamically by using Internet Explorer. To carry out this task, the script must perform the following steps:

1.
Create an instance of Internet Explorer.

2.
Open a blank Web page by navigating to "about:blank".

3.
Configure the user interface settings, and then show Internet Explorer by setting the Visible property to True.

4.
Create a reference to the Internet Explorer Document object, and then use the Open method to make a connection to the Document object. This allows your script to use commands such as WriteLn to write information to the browser window.

5.
Use the WriteLn method to create a title for the page, set the background color (bgcolor) to white, and create the message "Retrieving service information. Please wait." In addition to the message text, the HTML paragraph tag (<p>) is included. This ensures that the "progress bar" will be written on a separate line.

6.
Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to "impersonate."

7.
Use the ExecQuery method to query the Win32_Service class.

This query returns a collection consisting of all the services installed on the computer.

8.
For each service in the collection, use the WriteLn method to write an asterisk (*) in the browser window.

9.
Use the WriteLn method to write the message "Service information retrieved" to the browser window.

10.
Pause for 4 seconds (4,000 milliseconds). This pause is inserted simply to give the user a chance to see the message that service information has been retrieved.

11.
Close the Document object, and use the Quit method to dismiss Internet Explorer.

Listing 17.26 Tracking Dynamic Script Progress by Using Internet Explorer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

Set objExplorer = 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
objExplorer.Visible = 1

Do While (objExplorer.Busy)
Loop

Set objDocument = objExplorer.Document
objDocument.Open
objDocument.Writeln "<html><head><title>Service Status</title></head>"
objDocument.Writeln "<body bgcolor='white'>"
objDocument.Writeln "Retrieving service information. Please wait. <p>"

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer& "rootcimv2")
Set colServices = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service")

For Each objService in colServices
objDocument.Writeln "*"
Next

objDocument.Writeln "<br>Service information retrieved."
objDocument.Writeln "</body></html>"
Wscript.Sleep 4000
objDocument.Close
objExplorer.Quit

——————————————–
Tracking Script Progress in a Command Window

Microsoft® Windows® 2000 Scripting Guide

Running a script in a command window does not preclude you from using Internet Explorer as a way to track script progress; an Internet Explorer instance can be created and controlled from CScript in the same way it can be created and controlled from WScript.

At the same time, however, it is unusual for a command-line utility to generate a graphical progress indicator. Users might not recognize that the script running in the command window is tied to the progress indicator running in Internet Explorer. Because of this, you might want progress to be tracked in the same command window where the script is running.

Although you can track progress in a command window, there are at least two limitations:

• There are few formatting options available to you beyond using blank spaces and a mixture of lowercase and uppercase letters.

• You cannot erase the contents of the command window. For example, you might want to display a message such as, "Now completing Step 1 of 5." When this step is finished, you might want to erase the window and display, "Now completing Step 2 of 5." This cannot be done from a script. Even the cls command cannot be called from within a script; the command will run, but it will run within a new window that is automatically spawned. It will not clear the command window in which the script is running.

Of course, you can use Wscript.Echo to periodically display progress messages in a command window. For example, you might have script output that looks similar to this:

C:Scripts>cscript services.vbs
Now completing Step 1 of 5.
Now completing Step 2 of 5.
Now completing Step 3 of 5.
Now completing Step 4 of 5.

Another approach commonly used with command-line utilities is to display a series of dots (periods) as a script progresses:

C:Scripts>cscript services.vbs
Retrieving service information. This might take several minutes.
………………………………………………………………

Each time the script performs a subtask, a new dot is written to the command window. However, this cannot be done by using Wscript.Echo. Each time you call Wscript.Echo, the value is written to a new line. Because of this, your progress indicator would look like this:

C:Scripts>cscript services.vbs
Retrieving service information. This might take several minutes.
.
.
.
.

To append text to the command window, you must instead use the Wscript.StdOut.Write method and write each new value to the standard output stream.

Important

• You can write to the standard output stream only if the script is running under CScript. If a script running under WScript attempts to write to the standard output stream, an "invalid handle" error will result.

Scripting Steps
Listing 17.28 contains a script that tracks script progress in a command window. To carry out this task, the script must perform the following steps:

1.
Echo the message, "Processing service information. This might take several minutes."

2.
Create a variable to specify the computer name.

3.
Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to "impersonate."

4.
Use the ExecQuery method to query the Win32_Service class.

This query returns a collection consisting of all the services installed on the computer.

5.
For each service in the collection, use the Write method to write a period (.) to the standard output stream.

A production script would probably do additional processing during this stage (for example, saving service information to a database). In this sample script, service information is retrieved but no additional action is taken.

6.
Use the WriteLine method to write a blank line to the standard output.

7.
Echo the message, "Service information processed."

Listing 17.28 Tracking Script Progress in a Command Window

1
2
3
4
5
6
7
8
9
10
11

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

——————————————
Enumerating Scheduled Tasks

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
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
Next

———————————-
Scheduling a Task

strComputer = "."
Set objService = GetObject("winmgmts:" & strComputer)
Set objNewJob = objService.Get("Win32_ScheduledJob")
errJobCreated = objNewJob.Create _
("Monitor.exe", "********123000.000000-420", _
True , 1 OR 4 OR 16, , , JobID)
If Err.Number = 0 Then
Wscript.Echo "New Job ID: " & JobID
Else
Wscript.Echo "An error occurred: " & errJobCreated
End If

————————————————
Deleting a Single Scheduled Task

strComputer = "."
Set objService = GetObject("winmgmts:" & strComputer)
Set objInstance = objService.Get("Win32_ScheduledJob.JobID=1")
objInstance.Delete
—————————————————
Deleting All the Scheduled Tasks on a Computer

strComputer = "."
Set objService = GetObject("winmgmts:" & strComputer)
Set colScheduledTasks = objService.ExecQuery _
("SELECT * FROM Win32_ScheduledJob")
For Each objTask in colScheduledTasks
intJobID = objTask.JobID
Set objInstance = objService.Get_
("Win32_ScheduledJob.JobID=" & intJobID & "")
objInstance.Delete
Next

—————————————-

 Active Directory
——————-
Thanks,
http://sccm07.blogspot.com/

 

Leave a Reply

Your email address will not be published. Required fields are marked *