Use Powershell to Pass Embedded Credentials
I needed to pass the ID/password of a service account to a Microsoft HPC grid for some jobs we were submitting automatically. Powershell was able to do that pretty easily.
***WARNING*** This script reads a domain ID and password from an unencrypted file. Our implementation of this script used a protected file. Yours should too! You’ve been warned. I’m not responsible if your account password is compromised.
$domain = "[Your domain name]" $filename = "[Path to filename]\filename" $username = $domain + "\" + ($username.substring(($username.Length - 5),5)) $password = Get-Content $filename | ConvertTo-SecureString -AsPlainText -Force $credentials = New-Object System.Management.Automation.PSCredential($username,$password) |
A couple notes here. The $filename variable is used to get the entire path of the password file. For ease of scripting, I’ve created a file named the same as the user ID I’m using with no file extension. In the $username line, I’ve concatenated the $domain variable, a backslash, and the user ID that I’ve derived by taking the substring of the length of the $filename variable, minus the length of the ID, plus the length. There is a cleaner way to do this, but the ID I’m using will never change (yes, I said never), so I chose this method.
$username = $domain + "\" + ($username.substring(($username.Length - 5),5)) |
From that point, we read the password from the file and pipe it into the ConvertTo-SecureString commandlet. Since we are using a plaintext password here (see the warning above), we have to use the -AsPlainText and -
$password = Get-Content $filename | ConvertTo-SecureString -AsPlainText -Force |
The last line is used to actually pass the credentials to a variable that can be used in a script that requires authentication.
$credentials = New-Object System.Management.Automation.PSCredential($username,$password) |