Secure storage of credentials in PowerShell

If you search the internet, you will find many different blog/forum posts that show how to store credentials for later use in PowerShell. Most of these will point you toward one of these approaches:

  • Pipe a secure string to a text file
  • Read a secure string from the "host" (doesn't really work in unattended scenarios)
  • Encrypt using the private key of a certificate

Each of these has its disadvantages, which range from deleting the file to exposing the password.

I've settled on a new approach that balances the ease-of-use that PowerShell brings with the security required for sensitive data. The Office Developer Patterns and Practices (OfficeDevPnP) group has a library of cmdlets that includes Get-SPOStoredCredential. Despite the name, it can be used in all PowerShell scenarios.

TO use the cmdlet, you first log on to the computer using the appropriate account. Then, run the Credential Manager program that is included in Windows. Create a Generic credential (under Windows Credential). The cmdlet will read the credentials and return a NetworkCredential (for on-premises), a SharePoint Online Credential (for O365) or a PSCredential (which can be used anywhere).

You can get the code for the cmdlets from the GitHub repo, from which you can create an installer or xcopy-like deployment script.