I write a lot of PowerShell scripts where I need to access different kinds of services, servers and databases. Often these scripts needs to run on schedules in the background and so on.

Instead of having cleartext passwords scattered throughout the scriptfile I like to store a securestring version of the password in the script.

Normally you would build a credential object using something like this

That means that anyone who can open and read the scriptfile, will know what the password for the account in question is. Which is VERY BAD.

It would be better if we could create the SecureString from the content of itself (does that make sense?)

It turns out that you can in fact output the content of a securestring to a string using ConvertFrom-SecureString

The output is luckily not the unencrypted password we entered, it is a string containing the encrypted version of the password.

So in order to use this information as a password we need to reverse the process.

First we need to store the encrypted string in a variable

The next step is to create the credentials object

As you can see the magic stuff happens when you pipe the $password variable through ConvertTo-SecureString

So far I have not yet come up with a way the decrypt the encrypted string back to a readable value.

And the cool part is that it works everywhere you use –credentials (or at least for all the things I have tried so far)

If you prefer to store the password in an external file or a registry key you can that.

To write the securestring directly to the file you can use this

readhost AsSecureString | ConvertFromSecureString | Out-File password.txt

WARNING: This method will not prevent others from using the password, but at least its not in cleartext anymore.