Alternative Methods
As I mentioned earlier in this chapter, you're likely to run across other ways of performing WMI queries. For example, here's a short script that returns some information about a remote machine named Server1.
Set System = GetObject("winmgmts:{impersonationLevel=" & _
"impersonate}!//server1/root/cimv2:" & _
"Win32_ComputerSystem=""SERVER1""")
WScript.Echo System.Caption
WScript.Echo System.PrimaryOwnerName
WScript.Echo System.Domain
WScript.Echo System.SystemType
This doesn't follow the template-style query I've been using so far; in fact, it doesn't even use WQL. However, this example is functionally the same as the following one.
On Error Resume Next
Dim strComputer
Dim objWMIService
Dim colItems
strComputer = "server1"
Set objWMIService = GetObject("winmgmts:\\" & _
strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery( _
"Select * from Win32_ComputerSystem WHERE " & _
"Name = 'SERVER1'",,48)
For Each objItem in colItems
WScript.Echo "Caption: " & objItem.Caption
WScript.Echo "Domain: " & objItem.Domain
WScript.Echo "PrimaryOwnerName: " & objItem.PrimaryOwnerName
WScript.Echo "SystemType: " & objItem.SystemType
Next
There is practically no difference between the two. The first example uses GetObject to connect directly to a specified server's WMI service and retrieve a particular class (Win32_ComputerSystem) where the system's name is "SERVER1." The retrieved object is a WMI object, and can be used to display whatever information you want.
The second example uses the template I've used throughout this chapter (and the previous one) to fire off a WQL query, return an object collection, and then display the information. Which one is better? Technically, they're both identical. The second one has the benefit of being consistent with my other examples, and it lends itself easily to modification so that you can write more complex WQL queries to meet your specific needs. You're welcome to use either style, or even both if that's what you want to do.
|