An Azure Service Principal is a service account created in Azure AD and can be leveraged in PowerShell scripts for automation. It is recommended to use Service Principals for security reasons since they have separate credentials and very constrained rights.

You can either use password-based authentication or certificate-based authentication with Service Principals. In this article, only password-based authentication is covered. Certificate-based authentication is treated in the Microsoft article linked at the end of the page.

First of all, the Az Powershell Module is needed.

Install-Module -Name Az -AllowClobber -Scope Allusers

If you have multiple subscriptions, make sure you have selected the correct one.


Select-AzSubscription -SubscriptionId xxxxxxxxx

Now create the Principal:

$sp = New-AzADServicePrincipal -DisplayName PowershellAutomation

The $sp object contains a secret parameter (the password), which is not in clear-text and an ApplicationID, that will be used as the username. To decrypt the secret parameter use the following commands:

$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($sp.secret)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

In a script the $UnsecurePassword should not be hardcoded, instead, it should be saved as an encrypted XML file and decrypted when the script is executed. I wrote a post about securing credentials in PowerShell scripts, check it out:

Logging in is also straightforward. The Tenant id can be retrieved in the main page of Azure AD.

Connect-AzAccount -ServicePrincipal -Credential $credentials -Tenant xxxxx

When assigning rights, the newly created identity will be listed: