Script Tips

Logging on with Your Alter Ego

Make a WMI or ADSI connection with alternate credentials via this week's script.

There’s nothing more essential than making a WMI or ADSI connection using alternate credentials. One tricky bit about alternate credentials is getting a password—remember, you never hard-code passwords into a script.

Here’s a handy function you can use to collect a password from the command-line (it only runs on XP or 2003 and assumes the script is being run from CScript, not WScript):

Function GetPassword(strUsername)
   Dim objScriptPW, strPassword
   Set objScriptPW = CreateObject("ScriptPW.Password")
   WScript.Echo "Input password for " & _
      strUsername & " and press Enter:"
   strPassword = objScriptPW.GetPassword
   GetPassword = strPassword
End Function

I’ve used this function below to make a WMI connection using alternate credentials (that is, credentials other than those my script is executing under):

Dim objLocator, objWMI
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
On Error Resume Next
Set objWMI = objLocator.ConnectServer("Server1", _
   "root\cimv2", "Administrator", _
If Err <> 0 Then
   WScript.Echo "Error: " & Err.Description
   'you're connected - use objWMI.ExecQuery
   'to execute a query
End If

And a similar trick works for ADSI connections:

Dim objRoot, objDomain
Set objRoot = GetObject("LDAP:")
On Error Resume Next
Set objDomain = objRoot.OpenDSObject(_
   "LDAP://dc=company,dc=com", _
   "cn=AdminDon,ou=Admins,dc=company,dc=com", _
   GetPassword(""), _
If Err <> 0 Then
   WScript.Echo "Error: " & Err.Description
   'you're connected - objDomain, in this
   'example, represents the domain
End If

These are both handy bits to keep in your library of reusable script snippets.

About the Author

Don Jones is a multiple-year recipient of Microsoft’s MVP Award, and is an Author/Evangelist for video training company Pluralsight. Don is also a co-founder and President of, 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

comments powered by Disqus

SharePoint Watch

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.