PowerShell: Get-Credential from a file

If you routinely have to log into a separate domain, it can be a nuisance to always have to run Get-Credential. Plus writing scripts with a -Credential parameter is a nuisance because if you call Get-Credential in the script, it will always prompt you.


I run a separate lab network here, with an Active Directory domain of TreyResearch.net. I got tired of always having scripts prompt me for credentials, or even more annoying, have routine PowerShell commands against computers in the lab fail because I didn't have credentials for that domain. The answer is pretty simple -- first, I stored my password securely in a file with:

Read-Host -AsSecureString `
         | ConvertFrom-SecureString `
         | Out-File $Home\Documents\WindowsPowerShell\TCred.txt

Now, I can use that password to create a PSCredential object that I can pass into a script.

$tPW = Get-Content $home\Documents\WindowsPowerShell\TCred.txt `
         | ConvertTo-SecureString
$tCred = New-Object -TypeName System.Management.Automation.PSCredential `
                    -ArgumentList "TreyResearch\Charlie",$tPW


Because of the way SecureString works, and how Windows encrypts and decrypts objects, this password can only be read from the account that created it. Now, if I want to add a -Credential parameter to my scripts, I use the following:

      $Credential = $NULL

if ( $Credential ) {
   $tCred = $Credential
} else {
   $tPW = Get-Content $home\Documents\WindowsPowerShell\TCred.txt `
        | ConvertTo-SecureString 
   $tCred = New-Object -TypeName System.Management.Automation.PSCredential `
                       -ArgumentList "TreyResearch\Charlie",$tPW

ETA: if you create a script for this, you'll need to "dot source" the script to add the credential to your environment, but you can use that script in the pipeline to insert a credential into the pipeline. Or, add the relevant lines into your $Profile, and the credential is then available in your environment.

Leave a Reply

Your email address will not be published. Required fields are marked *