Archive

Archive for August, 2009

VB WMI Query Computer Attributes

August 2nd, 2009 No comments

By using a VB scripts we can perform a WMI (Windows Management Instrumentation) connection to a host to execute a query against.

Below is an example of a WMI query connecting to the host named “computer”, once connected will loop around each drive letter which is a hard drive displaying the drive letter and total disk space in GB

On Error Resume Next
Const HARD_DISK = 3

Set objWMIService = GetObject(“winmgmts:” & “{impersonationLevel=impersonate}!\\” & “computer” & “\root\cimv2″)

if Err.Number = 0 then
‘ Add WMI Query Script in here!

Set colDisks = objWMIService.ExecQuery (“Select * from Win32_LogicalDisk Where DriveType = ” & HARD_DISK & “”)
For Each objDisk in colDisks

Wscript.Echo objDisk.DeviceID + ” Disk Size (GB): ” + CStr(Round((((objDisk.Size / 1024)/1024)/1024),1))

Next

else
Wscript.echo “Could not connect to ” & “computer” & ” error ” & Err.Number
End If

Err.Clear

The above WMI query can be combined with an Active Directory query to make the script more versatile (further information is here), an example of this script is below:

On Error Resume Next
Const ADS_SCOPE_SUBTREE = 2
Const HARD_DISK = 3

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 from ‘LDAP://OU=MyServers,DC=Domain,DC=co,DC=uk’ ” & “Where objectClass=’computer’”
objCommand.Properties(”Page Size”) = 1000
objCommand.Properties(”Searchscope”) = ADS_SCOPE_SUBTREE
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
Wscript.Echo “Computer Name: ” & objRecordSet.Fields(“Name”).Value

Set objWMIService = GetObject(“winmgmts:” & “{impersonationLevel=impersonate}!\\” & objRecordSet.Fields(“Name”).Value & “\root\cimv2″)

if Err.Number = 0 then

‘ Add WMI Query Script in here!

else
Wscript.echo “Could not connect to ” & objRecordSet.Fields(“Name”).Value & ” error ” & Err.Number
End If

Err.Clear
objRecordSet.MoveNext
Loop

A number of WMI queries used can be found in the reference page WMI_Queries