Saving passwords for use in powershell scripts.

the get-credential command gets a username/password pair interactively.

these can be created and saved to a file, making this file a secure document means that only the user who created it can use it.

this means if you want to use the password in a script which will berun by a service account you need to create the password using that account. Do a run/as for a powershell prompt then doing the get-credential and save will work.

to create a credential using a plain text password (Don’t do this 😉 )

##
###
$username="bgates@microsoft.com"
$password = "XXXXXXXXXXXX"
$secureStringPwd = $password | ConvertTo-SecureString -AsPlainText -Force 
$UserCredential = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $secureStringPwd
###

To get a credential and save the password as a secure file.

#
$credential = Get-Credential
$credential.Password | ConvertFrom-SecureString | Set-Content c:scriptsencrypted_password4.txt
#

to read the credential password back and use it

#
$username="bgates@microsoft.com"
$securestringpwd = get-Content c:scriptsencrypted_password4.txt | ConvertTo-SecureString
$UserCredential = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $secureStringPwd

Once you have created the credential object you can use it anywhere that accepts a credential. MSonline, Azuread sharepoint.

# eg use it against a sharepoint site
$siteurl="https://microsoft.sharepoint.com/"
Connect-PnPOnline -Url $siteUrl -Credentials $USERcredential

About Jeff Turner

Technical director of Nano Tera Network Solutions.
This entry was posted in Powershell, VBS, VBA and other scripting., System Administration and tagged , . Bookmark the permalink.