Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
### Written with Azure PowerShell Module version 4.4.1
# Fill in the below variables
$SPDisplayName = 'User Account SP'
$SPPassword = 'password' # Password is required
$ResourceGroup = '' # Leave blank for subscription scope as to where to apply the SP role to
$Role = 'Contributor' # Could also be 'Owner'
### Choose Subscription
$subscription = Get-AzureRmSubscription | Out-GridView -Title "Select the Azure subscription that you want to use ..." -PassThru
Select-AzureRmSubscription -SubscriptionId $
$SubscriptionId = $
#region Setup the Service Pricipal in Azure AD
if ($ResourceGroup -eq '')
$Scope = "/subscriptions/" + $SubscriptionId
$Scope = (Get-AzureRmResourceGroup -Name $ResourceGroup -ErrorAction Stop).ResourceId
# Create Service Principal for the AD app - This step skips New-AzureRmADApplication but creates an Azure AD application
$ServicePrincipal = New-AzureRmADServicePrincipal -DisplayName $SPDisplayName -Password $SPPassword
Get-AzureRmADServicePrincipal -ObjectId $ServicePrincipal.Id
$NewRole = $null
$Retries = 0;
While ($NewRole -eq $null -and $Retries -le 30)
# Sleep here for a few seconds to allow the service principal application to become active (should only take a couple of seconds normally)
Sleep 1
New-AzureRMRoleAssignment -RoleDefinitionName $Role -ServicePrincipalName $ServicePrincipal.ApplicationId.Guid -Scope $Scope -ErrorAction SilentlyContinue
$NewRole = Get-AzureRMRoleAssignment -ObjectId $ServicePrincipal.Id -ErrorAction SilentlyContinue
#region Remove the Serivice Principal - ONLY IF YOU REALLY NEED TO
#Remove-AzureRmADServicePrincipal -ObjectId $ServicePrincipal.Id -Force
Get-AzureRmADApplication | ? {$_.ApplicationId -eq $ServicePrincipal.ApplicationId.Guid} | Remove-AzureRmADApplication -Force
#region TEST Logon to Azure & choose the Azure subscription using an SPN
### Test log into Azure with the new SP account
$secpasswd = ConvertTo-SecureString $SPPassword -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential ($ServicePrincipal.ApplicationId, $secpasswd)
$TenantId = $subscription.TenantId
Login-AzureRmAccount -Credential $cred -ServicePrincipal -TenantId $TenantId
$Subscription = (Get-AzureRmSubscription | Out-GridView -Title "Choose a Source & Target Subscription ..." -PassThru)
Select-AzureRmSubscription -SubscriptionId $Subscription.Id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment