This post is the second in a series on short posts with some of my favorite PowerShell tips and tricks (first one here, in case you missed it).
This next script is another building block I use in many other scripts – especially ones where I know I’m going to be connecting to the same credentials continually, and especially if I need to run a scheduled task that I want to be 100% automated.
Start by modifying your $credFilePath – either pick some known location to save the XML file at the end, or simply run it as is, and the script will save the XML file to your current directory. You can move it to your final destination after you’re done.
$credFilePath = “.O365Credential.xml” #xml file that holds the global admin login information
The script doesn’t require any additional parameters or changes – just run the script as is, and it will prompt for username and password.
Username:
$admAccount = Read-Host “Enter admin logon (UPN)”
Then password:
$admPassword = Read-Host -AsSecureString “Please enter admin password”
After that, the script will convert the password to a secure credential object, and export the credentials to an XML file:
$admPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($admPassword))
New-Object System.Management.Automation.PSCredential($admAccount, (ConvertTo-SecureString -AsPlainText -Force $admPassword)) | Export-CliXml $credFilePath
Finally, I clear out the $admPassword variable, just to ensure that it’s not discoverable from the shell:
$admPassword = $null
And that’s it, basically – unlike my connection scripts, I don’t use this script in my day to day work – just to create and securely store the credentials that I need for the other scripts I’m building/running all the time. Once you have your XML file created, adding it to your scripts is easy, simply add the following line to your code:
$credential = Import-Clixml .O365Credential.xml
Obviously, make sure that you’re either pointing to the exact location of the XML file or make sure that it’s saved in the directory that you’re running the script from – either one. Also, this credential file will only work for the user context it was created with. If you intend for a script to run as a scheduled task using a service account, log in as that account and create the credentials that way. If you create it with your account, and then schedule the script to run with another account, it will give you an error and your script will fail.
This script is available in its entirety on GitHub – hope this helps!
😀