Alternate Credentials - ADSI and WMI
Here’s an example of using alternate credentials to connect to either WMI or ADSI. Note that WMI doesn’t allow alternate credentials if you’re connecting to the LOCAL computer - only for remote connections. Both of these examples use a function. GetPassword, which I’ve included. This prompts you for a password on the command-line (it’ll give you an error if run with WScript) and hides what you’re typing.
- '
- ' ScriptingAnswers.com Essentials - by Don Jones
- '
- ' Alternate Credentials
- ' This shows how to make a connection, using alternate
- ' credentials, using both WMI or ADSI. It also shows
- ' a very useful function that will gather a password,
- ' since it's a horrible idea to hardcode a password
- ' into any script
- '
- ' You're not intended to RUN this script - it just makes
- ' the connections; it doesn't do anything with them.
- ' Copy and paste appropriate code into your own script
- 'here's the WMI connection using alternate credentials
- Dim objLocator, objWMI
- Set objLocator = CreateObject("WbemScripting.SWbemLocator")
- On Error Resume Next
- Set objWMI = objLocator.ConnectServer("Server1","root\cimv2","Administrator",GetPassword("Administrator"))
- If Err <> 0 Then
- WScript.Echo "Error: " & Err.Description
- Else
- 'you're connected - use objWMI.ExecQuery to execute a query
- End If
- 'here's the ADSI connection using alternate credentials
- 'you'll obviously modify the LDAP query to match whatever
- 'AD object you're trying to get hold of. Notice that the
- 'alternate credential is an LDAP path!
- Const ADS_SECURE_AUTHENTICATION = 1
- 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("AdminDon@company.com"), ADS_SECURE_AUTHENTICATION)
- If Err <> 0 Then
- WScript.Echo "Error: " & Err.Description
- Else
- 'you're connected - objDomain, in this example, represents the domain
- End If
- ' Here's the password-collection Function
- ' It does assume we're (a) running on WinXP or 2003,
- ' and (b) running from CScript, not WScript
- ' Run CSCRIPT //H:cscript to make CScript your Default
- ' script host.
- 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
Tags: adsi, alternate credentials, password, prompt, VBScript Scripts, wmi










