Do you need to use passwords in your script. Yes, most of System Administrators needs to use it in order to fully auotmate script. Specially when you are working with multiple domains with no trust, workgroups and DMZ zones.
I have seen lot of people just put their passwords in plan text in the scripts. But is it safe, No. Well there are few options to do so.
You can use Get-Credential, if you arw working with powershell and interactive session. But most of us needs to run scripts in background. So you need to find a way to specify password securely in script.
Answer is store the password in file but encrypted. This can be done using ConvertFrom-SecureString
Using following command, it will store the password to text file which be encrypted.
read-host -assecurestring | convertfrom-securestring | out-file C:\Temp\MySecurePassword.txt
Start Typing your password. Press Enter to save the encoded password to text file.
At this point, you will see the neew text file cerated.
This will encode the password so it cannot be read as plain text.
You dont have to use text file, you can other file types as well.
NOTE: This method has some limitation that it will only work for the same user on the same machine. No other user or profile on same machine or any other machine can read or decrypt this file. Decryption can only be done via same user on same machine. I hope it makes sense.
To read it, use the following code which will automatically decode it.
$Mypassword = get-content C:\Temp\MySecurePassword.txt | convertto-securestring
At this point you may need to decrypt the password to plain text. Use the following code to do so. I have been using this Function for long time, but forgot where I used this from.
#A Generic Function for Converting Security.SecureString Objects to Plain Text Strings
param( [Parameter(Mandatory=$true)][System.Security.SecureString] $SecurePassword)
# Create a “password pointer”
$PasswordPointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
# Get the plain text version of the password
$PlainTextPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto($PasswordPointer)
# Free the pointer
# Return the plain text password
#Convert Secure password into plain text
$MyPlainTextPass = ConvertFrom-SecureToPlain $Mypassword
Now you can create the Credential Object if required
$MyCredential = new-object -typename System.Management.Automation.PSCredential -argumentlist $MyUserName,$MyPassword
Just in case you need to use the password from Crdential Object and check if it is the right one. But you will be need to convert it to plain text first.
$MyPlainTextPassFromCredObj = ConvertFrom-SecureToPlain $MyCredential.password