---
title: How to Create Azure Service Principals in PowerShell
description: Learn how to create Azure service principals using PowerShell, enabling secure automation for managing Azure resources like virtual machines.
canonical: https://adamtheautomator.com/powershell-service-principals/
---

# How to Create Azure Service Principals in PowerShell

> Learn how to create Azure service principals using PowerShell, enabling secure automation for managing Azure resources like virtual machines.

Source: https://adamtheautomator.com/powershell-service-principals/

---

- How to Create Azure Service Principals in PowerShell Tap to hide Home

- Tutorials

- Guidebooks

- Instructors

- Get Paid to Write

- Advertising

- Recommended Resources

- About Adam

                Search for:

-

-

-

-

# How to Create Azure Service Principals in PowerShell

        Published:30 September 2024 - 2 min. read

- Azure
- Azure PowerShell
- PowerShell

          [](https://adamtheautomator.com/author/adam-bertram/)

            [Adam Bertram](https://adamtheautomator.com/author/adam-bertram/)

            Read [more tutorials](https://adamtheautomator.com/author/adam-bertram/) by Adam Bertram!

-

-

        [](https://specopssoft.com/product/specops-password-auditor/?utm_source=adamtheautomator&utm_medium=referral&utm_campaign=adamtheautomator_referral_na&utm_content=display)
        Audit Active Directory for stale users, weak passwords, and other security risks with [Specops Password Auditor](https://specopssoft.com/product/specops-password-auditor/?utm_source=adamtheautomator&utm_medium=referral&utm_campaign=adamtheautomator_referral_na&utm_content=text).

Table of Contents

- Step 1: Install Required Azure Modules
- Step 2: Create an Azure AD Application
- Step 3: Create a Service Principal
- Step 4: Generate a Client Secret
- Step 5: Assign Permissions to the Service Principal
- Step 6: Authenticate Using the Service Principal
- Step 7: Test the Authentication
- Step 8: Rotate Client Secrets
- Conclusion

                XFacebookLinkedIn

In this blog post, you'll learn how to create an Azure service principal using PowerShell, which is essential for automating tasks and securely managing resources in Azure. We will walk through the process of creating an Azure Active Directory (AD) application, generating a client secret, and assigning the necessary permissions for managing virtual machines (VMs). This method allows applications to securely authenticate and interact with Azure resources.

### Step 1: Install Required Azure Modules

Start by installing the necessary module, `Az.Resources`, which contains the cmdlets required to manage Azure resources, including creating and managing Azure AD applications and service principals.

Install-Module -Name Az.Resources

### Step 2: Create an Azure AD Application

Now, create an Azure AD application, which acts as the identity for managing Azure resources. Here, we create an app called "VMManagement" that will be used for managing virtual machines.

$vmManagementApp = New-AzADApplication -DisplayName VMManagement

### Step 3: Create a Service Principal

After creating the Azure AD application, generate a service principal. This principal allows us to manage resources in Azure using the app's identity.

$sp = New-AzADServicePrincipal -ApplicationId $vmManagementApp.AppId

### Step 4: Generate a Client Secret

We now need to create a client secret that the service principal will use for authentication. This secret is generated and stored securely.

$clientSecret = New-AzADAppCredential -ObjectId $vmManagementApp.Id
$clientSecret.SecretText | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File -FilePath C:\AzureAppPassword.txt

This command creates a client secret for the app and saves it in an encrypted format to a file. This file will be used later to authenticate the application.

### Step 5: Assign Permissions to the Service Principal

The next step is to assign the necessary roles to the service principal. In this case, we grant the "Virtual Machine Contributor" role, allowing the service principal to manage VMs.

$subscriptionId = (Get-AzSubscription).Id
New-AzRoleAssignment -ObjectId $sp.Id -RoleDefinitionName "Virtual Machine Contributor" -Scope "/subscriptions/$subscriptionId"

This grants the service principal permissions to manage VMs in the specified subscription.

### Step 6: Authenticate Using the Service Principal

To test the authentication, use the client secret stored earlier to log in with the service principal.

$pass = (Get-Content -Path 'C:\AzureAppPassword.txt' | ConvertTo-SecureString)
$azureAppCred = New-Object System.Management.Automation.PSCredential($vmManagementApp.AppId, $pass)
$subscription = Get-AzSubscription
Connect-AzAccount -ServicePrincipal -SubscriptionId $subscription.Id -TenantId $subscription.TenantId -Credential $azureAppCred

This command authenticates the service principal using the application ID and the secure password.

### Step 7: Test the Authentication

Now that you've authenticated, test the authentication by retrieving a list of virtual machines in the subscription.

Get-AzVM

If successful, the command will return a list of VMs, confirming that the service principal is working as expected.

### Step 8: Rotate Client Secrets

For security, it's essential to periodically rotate client secrets. The script below automates this process, generating a new client secret and removing the old one.

[CmdletBinding()]
param(
    [Parameter(Mandatory)]
    [string]$AdApplicationName,

    [Parameter()]
    [string]$OutputFilePath = "C:\NewAzureAppPassword.txt"
)

$adApp = Get-AzADApplication -DisplayName $AdApplicationName
$sp = Get-AzADServicePrincipal -ApplicationId $adApp.AppId
$newClientSecret = New-AzADAppCredential -ObjectId $adApp.Id
$newClientSecret.SecretText | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File -FilePath $OutputFilePath

$oldClientSecret = (Get-AzADApplication -DisplayName $AdApplicationName).PasswordCredentials | Sort-Object StartDateTime | select -First 1
Remove-AzADAppCredential -ApplicationId $adApp.AppId -KeyId $oldClientSecret.KeyId

This script rotates the client secret, generating a new one and securely saving it to a file.

### Conclusion

By following these steps, you've successfully created a service principal, granted it the necessary permissions, authenticated using the client secret, and tested it. Additionally, you’ve implemented a process to rotate client secrets regularly, enhancing the security of your Azure applications. This setup ensures your automation scripts can securely access and manage Azure resources without manual intervention.

  Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

  [Explore ATA Guidebooks](https://adamtheautomator.com/ata-guidebooks/)

## More from ATA Learning and Partners

- ### Recommended Resources! Recommended Resources for Training, Information Security, Automation, and more!

- ### Get Paid to Write! ATA Learning is always seeking instructors of all experience levels. Regardless if you’re a junior admin or system architect, you have something to share. Why not write on a platform with an existing audience and share your knowledge with the world?

- ### ATA Learning Guidebooks ATA Learning is known for its high-quality written tutorials in the form of blog posts. Support ATA Learning with ATA Guidebook PDF eBooks available offline and with no ads!

## Categories

- IT Ops

- Cloud

- DevOps

- Home Ops

- Information Security

- Software Development

## Site

- Home

- Tutorials

- Guidebooks

- Instructors

- Get Paid to Write

- Advertising

- Recommended Resources

- About Adam

        Copyright 2026&copy; ATA Learning | [Privacy Policy](https://adamtheautomator.com/privacy/)

                                                        Don't be left behind with the ATA Learning Newsletter!

Looks like you're offline!
