Store encrypted password in a PowerShell script

Title:


Store encrypted password in a PowerShell script


Description:


Some times  scripts needs to run on schedule base  in the background. That time password need to be secure with out show password as plain text.




Plain password: sudip@2006
Encrypted password : 01000000d08c9ddf0115d1118......


Note: Plain password can be read by humans and remind that to miss use :) , but encrypted password will be in lengthy and not meaningful format.


Implementation:


Step1:
Below code generate the encrypted password in C:\Password3.txt file  for  sudip@2006

"sudip@2006" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\Password3.txt"


Example of C:\Password3.txt file


01000000d08c9ddf0115d1118......


above step don't  mention in script.

Step2: Provide username and encrypted password path instead of plain password.

$username ="sudiplakku@myoffice365.onmicrosoft.com"
$password = Get-Content "C:\Password3.txt"
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $username,($password | ConvertTo-SecureString)

Connect-SPOService -Url https://myoffice365-admin.sharepoint.com -Credential $cred


Note: it connected to SharePoint Online with out enter the plain password.
Step3: Write code here
Get-SPOSite


=================Done===============================
Also we can use below way if you do not want file reference.

$password = "01000000d08c94cb4a61c6560bef21f0000000039adbb78dbf2e8e03ef92068ce5fe48c448f7db7074b2eca50402497

$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $username,($password | ConvertTo-SecureString)