Many times there is a need to store password in PowerShell script. Unfortunately to leave password in script is insecure solution and might cause an issue.

So, what to do if there is a need to have password in a script and we don’t want to have it embedded in clear-text in script?

Best way is to encrypt it and store in the file and then re-use it when required.

Create file with encrypted password

$secureString = Read-Host -AsSecureString "Enter a secret password"
$secureString | ConvertFrom-SecureString | Out-File C:\Scripts\storedPassword.txt

Use encrypted password in script

$secureString = Get-Content -Path C:\Scripts\storedPassword.txt | ConvertTo-SecureString
Remember that password has to be encrypted on the account which will be running the script. So, in case you plat to use Task Scheduler to run PowerShell script, start PowerShell windows as particular user and then create file with encrypted password.