Thursday, 22 September 2016

Store a credential to a file in Powershell

Store a credential to a file in Powershell

In Powershell you can use SecureString to store a password for a user account. Once saved, the encrypted password can be decrypted by the same Windows user for later use.

This is handy if you need to supply a PSCredential object to a cmdlet in a scheduled script.

To store the credential, enter the username and password into a PSCredential object while logged into the user account which will be used to execute the script.

$credential = Get-Credential

Once you have the object, convert the password from a secure string and output to a file

$credential.Password | ConvertFrom-SecureString | Out-File .\credentialpw.bin -enc ASCII

Once the password is in the file, you can re-import the password to a credential object as follows.

$userName = "myuser"
$secPassword = Get-Content .\credentialpw.bin | ConvertTo-SecureString
$newCredential = New-Object System.Management.Automation.PsCredential($userName,$secPassword)

The $newCredential object can now be used to pass to a cmdlet.

If you try to use the password file as a different Windows user, the password file cannot be converted to a SecureString:

Keep in mind that the password as a securestring object can be reversed back to plain text, so this should not be used to keep the password safe from the user account it is stored by.

$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secPassword)
$PlainText = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

The above commands will allow you to recover the plain text password - but only as the user that originally saved the credential.

No comments:

Post a Comment

Please be nice! :)