How-to create a credential object for PowerShell automation

Being able to automate tasks for Office 365 with PowerShell without any form of user intervention requires a PowerShell script to be able to authenticate by itself. In other words, some form of credential (username / password) storage is required. Two common options are:

  • File Storage
  • Windows Credential Manager

File Storage

With file storage, one file can be used, but using two files is more straightforward.

The following code creates the files on disc:

Read-Host | Out-File -LiteralPath 'D:\PowerShell\username.txt'
Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File -LiteralPath 'D:\PowerShell\password.txt'

A credential object is now created with the following code:

$username = Get-Content -LiteralPath 'D:\PowerShell\username.txt'
$password = Get-Content -LiteralPath 'D:\PowerShell\password.txt' | ConvertTo-SecureString
$credential = New-Object -TypeName 'System.Management.Automation.PSCredential' -ArgumentList $username,$password

It is recommended to name the files differently than “username.txt” and “password.txt”, but for the intend of better understanding this blog post, they are called this way in the sample code above.

Windows Credential Manager

PnP PowerShell has native support for the Windows Credential Manager as described here. For other Office 365 connections, like Connect-AzureAD, a PowerShell module named “CredentialManager” can be used.

After installing the module, the cmdlet Get-StoredCredential can be used to retrieve a credential object. Example: Retrieving a credential for a target named “O365”:

$credential = Get-StoredCredential -Target 'O365'

Credentials can be manually added to the Windows Credential Store or via the PowerShell cmdlet New-StoredCredential. Example: Storing a credential with a target named “O365”:

New-StoredCredential -Target 'O365' -UserName … -Password …

References

[1] The PowerShell Gallery
[2] The PowerShell Gallery module “CredentialManager”

Leave a Reply

Your email address will not be published. Required fields are marked *