Create, Store & Use Encrypted Passwords With PowerShell

This is just a neat little “tactic” I use when I need to connect to the same machine over and over again but don’t want to drive myself insane with having to constantly enter the same username and password. For example, when testing a script.

First you need to enter your password, in plain text, into this script so that it can get the password. This a perfectly safe as it will only be at this point where the password is in plain text.

$password = "PUT PASSWORD HERE" | ConvertTo-SecureString -AsPlainText -Force

This gets the password that you just entered and encrypts it and also puts it into the variable “password”

Now you need to convert the password to an encrypted string of characters using the below command:

$Password2 = $password | ConvertFrom-SecureString | Out-File "PATH TO TEXT FILE TO STORE PASSWORD"

This puts the encrypted password into the text file for later use.

Now, whenever you need to connect to a machine, you can put this into a variable along with the username. Then put them together into a credential and away you go:

$Username = "DOMAIN\username"

$EcryptedPassword = Get-Content "LOCATION TO TEXT FILE" | ConvertTo-SecureString

$Credential = New-Object System.Management.Automation.PSCredential($Username, $EncryptedPassword)

This builds the credential which you can now use with something similar to below:

Invoke-Command -Credential $Credential -ScriptBlock {echo "test"} -ComputerName "COMPNAME" -Authentication CredCSSP

Enjoy!


Leave a Reply