Passing Powershell Credentials securely

Recently I came across the need to send credentials inside of a Powershell script. To make a long story short it was to run an invoke command on a remote computer. I really did not like the idea of having a password in a script so I started looking around for solutions. Eventually I came to a really simple but effective article that went over a very straightforward example.

I took that and essentially broke it into a couple of steps.

  1. Create the encrypted password in a file
  2. Read in the file in the script and decrypt it to be used during execution

Step 1: Create your encrypted password file.

Run the following on a powershell prompt. No need to make a powershell script to do this. You will then take this password file to be used later.

(get-credential).password | ConvertFrom-SecureString | set-content "c:\your_encrypted_password.txt"


Step 2: Use the encrypted password file in your automation scripts.

Here is a simplified snippet of code using the encrypted password:

# The magic line of code is below. Converting your password file to be used as part of a credential variable.

$encrypted = Get-Content  c:\your_encrypted_password.txt   | ConvertTo-SecureString 

$cred = New-Object System.Management.Automation.PsCredential($username, $encrypted)  # Your Credential used for another command.

New-ADComputer -Name $var_svr_name -SamAccountName $var_svr_name -path $var_ou_path -Credential $cred -server $var_domain -Description $var_co_description -Verbose