Retrieving credentials securely with PowerShell

In a recent article I highlighted how you can securely save credential from PowerShell to a local file using the Export-Clixml command here:

Saving credentials securely with PowerShell

The idea with saving credentials securely is that you can now get to them quickly and easily. Just as easily in fact as embedding them into your PowerShell (which is a major no-no). So how do you do that?

You basically use the the import-clixml command like so:

$clientidcreds = import-clixml -path .\clientid.xml

to retrieve them. This will open the client.xml in the current directory, read in the encrypted values (username and password) and store them in the variable $clientidcreds.

Now $clientidcreds.password is a secure string, which means it can’t easily be used as a normal string in PowerShell. No problemo, now jus run the command:

$clientid = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($clientIdcreds.password))

and $clientid will have the plain text variable you initially saved and exported to the secure  XML file.

This is pretty neat eh? It allows you to securely save items such as oAuth and API keys in a secure file on you machine and then recall them quickly and easily with the above commands and use them in your PowerShell code.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s