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.
- Create the encrypted password in a file
- 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.
#EXAMPLE USE OF A CREDENTIAL
New-ADComputer -Name $var_svr_name -SamAccountName $var_svr_name -path $var_ou_path -Credential $cred -server $var_domain -Description $var_co_description -Verbose
Ben Tuma
Over 20 years of experience in the Information Technology field. I love technology and seeing how it changes and impacts peoples lives for the better. I have healthy appetite for innovation and problem solving.
I am sharing my knowledge and challenges in hopes to help others as we constantly face ever changes problems in IT and technology.