Script Tips

Split Personality

Using alternate credentials in WMI connections.

It’s so common to see WMI connections made using the winmgmts:// moniker that you may not realize WMI has a lot more flexibility available to you. For example, this common connection:

Set objWMI = GetObject("winmgmts:\\server2\root\cimv2")

will connect to the root/cimv2 namespace on Server2, using your current credentials. By default, the current version of WMI will allow Server2’s WMI service to impersonate your credentials for whatever queries you execute.

But what if you don’t have the necessary -- usually Administrator -- permissions on Server2? You’ll need to use a different method of connecting to WMI, so that you can specify alternate credentials. Here's a script for that:

Const wbemImpersonationLevelImpersonate = 3

'specify credentials
strComputer = "server1"
strUser = "Administrator"
strPassword = InputBox("Enter password for " & strUser & _
" on " & strComputer

'connect to WMI
Set objSWbemLocator = _
  CreateObject("WbemScripting.SWbemLocator")
objSWbemLocator.Security_.ImpersonationLevel = _
  wbemImpersonationLevelImpersonate
Set objSWbemServices = _
  objSWbemLocator.ConnectServer(strComputer, _
  "root\cimv2", strUser, strPassword)

Note that this trick won’t work against the local computer -- you can never specify alternate credentials for local connections (if you need to, run the script by using the RunAs command). Also note that I didn’t hard-code the password in the script; I prompted for it, using InputBox(). There’s no safe way to hard-code credentials into a script; if you’re thinking the Microsoft Script Encoder will protect the credentials from prying eyes, do a Google search for "Microsoft Script Decoder" and think again.

About the Author

Don Jones is a multiple-year recipient of Microsoft’s MVP Award, and is Curriculum Director for IT Pro Content for video training company Pluralsight. Don is also a co-founder and President of PowerShell.org, a community dedicated to Microsoft’s Windows PowerShell technology. Don has more than two decades of experience in the IT industry, and specializes in the Microsoft business technology platform. He’s the author of more than 50 technology books, an accomplished IT journalist, and a sought-after speaker and instructor at conferences worldwide. Reach Don on Twitter at @concentratedDon, or on Facebook at Facebook.com/ConcentratedDon.

comments powered by Disqus
Most   Popular