In this blog post, I will show you how to use passwords in a PowerShell script without saving them in cleartext.
How It’s Done
I have a scripting library that I use with task scheduler to run scripts.
In many of my script, I use a username and password to login to different cloud services.
Create a password file
The first step I will take to secure my password is by creating a file called password.txt.
This file will keep the password in an encrypted format.
After I created the file, I will run the following script.
The script will prompt for a username and password.
I will run the script to save them.
$credential = Get-Credential $credential.Password | ConvertFrom-SecureString | Set-Content password.txt
At this stage, I have the password encrypted, and now I will integrate it into my code.
In the example below, I am using the password to connect to Office 365.
$powerUser = "email@example.com" $password = Get-Content .\password.txt | ConvertTo-SecureString $adminCredential = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $powerUser,$password Connect-MsolService –Credential $adminCredential
Make sure the script and password file are located in the same directory.