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 machine. 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 = "terminator.movie.edu"
set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

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

strComputer = "terminator.movie.edu"
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 any other function.

This was a quick introduction into WMI scripting. We’ll cover additional tasks, such as invoking an action or modifying properties of an object, as we walk through specific DNS examples later in the chapter. Now, back to the good stuff ...

Get DNS on Windows Server 2003, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.