Store Credentials in PowerShell
From time to time, we have to perform actions in a PowerShell script for which the user account executing the script does not have sufficient privileges. We usually get around this by performing those specific actions using a different user’s credentials in our script. For example, we have an on-premises AD user account executing a script that performs a bunch of on-prem Active Directory tasks. Say we want to integrate into this script other cloud actions in Azure for example on cloud mailboxes to which our on-prem user account does not have sufficient access. In this scenario we can store credentials in PowerShell for our cloud admin user account that has sufficient cloud privileges.
Saving the password
First, we need to save the cloud user’s encrypted password in a file. To do this, we launch a PowerShell session as the user account that will be executing the script and on the same server/workstation that the script will run on. It is very important that we run it as the executing user of the script and on the same server/workstation or else the call the retrieve the password at script run-time will not work.
Step 1 – Run PowerShell as different user
Step 2 – Enter the credentials of the user account executing the script
Once we have our PowerShell session open, we can proceed to save the encrypted password to a file.
Step 3 – Save encrypted password to a file
Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File c:\CloudCred
Note: after running the above command, you will type in the cloud account’s password and then hit enter again, at which point the file will be created.
Retrieving the password
We are now ready to utilize the encrypted password file in our script.
Step 4 – Get the password file contents
$MyPassword = Get-Content C:\CloudCred | ConvertTo-SecureString
Step 5 – Create PSCredential object for cloud user
$MyCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "CloudUser",$MyPassword
Now that we have PSCredential object (i.e $MyCredential), we can utilize it for, say, connecting to the Azure MSOL Service. Ofcourse, as our cloud user. Here is an example…
$MySession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $MyCredential -Authentication Basic –AllowRedirection Import-PSSession $session -AllowClobber Connect-MsolService -Credential $MyCredential
For more info on Secure Strings see https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/convertto-securestring?view=powershell-6.