Authentication with WMI

So far, the examples we've shown assume that the caller of the script has the necessary rights to access the WMI information on the target computer. In most cases in which you are trying to automate a task, that may not be the case. Luckily, using alternate credentials in WMI is very straightforward.

Previously, to connect to a WMI namespace, we would have used the following:

strComputer = ""
set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

But let's say that the person calling the script does not have any privileges on srv01. We must now use the following:

strComputer = ""
strUserName = "administrator"
strPassword = "password"

set objLocator = CreateObject("WbemScripting.SWbemLocator")
set objWMI = objLocator.ConnectServer(strComputer, "root\cimv2", _
                                      strUserName, strPassword)

We've replaced the single call to GetObject with a call to CreateObject to instantiate a WbemScripting.SWbemLocator object. The SWbemLocator object has a method called ConnectServer, which allows us to specify the target machine, username, and password.[1] We can then use the object returned from ConnectServer to get the instances of a class, perform a WQL search, or carry out any other function.

[1] Obviously, it is less than ideal to include passwords in plain text scripts. An alternative would be to require the user to use the runas command to authenticate as the privileged user, or if you plan on running the script via Scheduled Tasks, ...

Get Windows Server Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.