Storing password information securely in PowerShell Scripts

When folks are getting started with PowerShell logging into Office 365, often one will user Get-Credential to force PowerShell to prompt for a username and password.  That credential is then passed into operations such as logging into Office 365 or using the SharePoint PNP PowerShell modules.

When it comes time to automate these operations, I’ve seen far too many folks just hardcode a username and password in the script.  From my perspective, not the best idea from a security standpoint.  This simple script will allow you to securely capture your password and store it securely in a file on your system.  I would strongly suggest using NTLM permissions to lock access to the password file to only the user account your script will be running as.

 

Hope you find this useful:

 

SetPassword.ps1
$baseFilePath = “e:\PowerShell\”
$filePath =  $baseFilePath + “password.txt”

(Get-Credential).Password | ConvertFrom-SecureString | Out-File $filePath

 

Get Password Function

Function Get-StoredCredential
{
param( [string]$UserName, [string]$BasePath)

 

$File = $baseFilePath + “password.txt”
$FileContent = Get-Content $File
return New-Object -TypeName System.Management.Automation.PSCredential ` -ArgumentList $UserName, ($FileContent | ConvertTo-SecureString)
}