Monthly Archives: April 2016

In the field, occasionally I stumble over Azure AD or Office 365 support scripts that contain hard coded credentials for the Connect-MsolService cmdlet. This is mainly because these scripts are intended to run regularly in the background and therefore need to establish a connection without user interaction (caused by Get-Credential). With this post I want to draw attention to a smarter approach that eliminates the risk of exposing plain-text passwords in script files.

In fact, saving/restoring credentials to/from file is the perfect use case for Export-CliXml and Import-CliXml. You can pipe any object to Export-CliXml. It creates an XML-representation of the object and saves it in a file. You can re-create the object based on the XML file with Import-CliXml. The best thing about it is that the Export-CliXml cmdlet encrypts credential objects with DPAPI to make sure that only your user account can decrypt the contents of the original credential object.

In the code above, the file in which the credential is stored is represented by (‘{0}.credential’ -f $MyInvocation.MyCommand.Name) which resolves to the file name of the script plus the .credential suffix. The file will be saved along with the PowerShell Profile ($profile). If the .credential file exists the code will leverage Import-CliXml to restore the credential object, if not it will invoke Get-Credential and save the credentials with Export-CliXml. In either case the credential variable exposes the credential object.

Please note anyway: Generally you should avoid storing credentials in plain-text files. Opt for this approach only if there’s no better alternative.