Skip to content

Instantly share code, notes, and snippets.

@marckean
Last active September 20, 2016 04:35
Show Gist options
  • Save marckean/4eb9f3cde4cbd35c32f175361bc2465d to your computer and use it in GitHub Desktop.
Save marckean/4eb9f3cde4cbd35c32f175361bc2465d to your computer and use it in GitHub Desktop.
$DisplayName = 'My-SPN'
$Domain = 'company.com'
$Password = 'Password!'
Function SPN-Removal ($DisplayName){
if(Get-AzureRmADApplication | ? {$_.DisplayName -eq $DisplayName}){
$app = Get-AzureRmADApplication | ? {$_.DisplayName -eq $DisplayName}
Remove-AzureRmADApplication -ObjectId $app.ObjectId.Guid -Force
}
if(Get-AzureRmADServicePrincipal -SearchString $DisplayName){
$appsp = Get-AzureRmADServicePrincipal -SearchString $DisplayName
Remove-AzureRmADServicePrincipal -ObjectId $appsp.Id
}
}
Function SPN-Creation ($Subscription, $DisplayName, $Domain, $Password){
$app = New-AzureRmADApplication `
-DisplayName $DisplayName `
-HomePage "https://$Domain/$DisplayName" `
-IdentifierUris "https://$Domain/$DisplayName" `
-Password $Password
New-AzureRmADServicePrincipal -ApplicationId $app.ApplicationId.Guid
Start-Sleep -Seconds 10 # Until it really creates it
New-AzureRmRoleAssignment -RoleDefinitionName 'Contributor' -ServicePrincipalName $app.ApplicationId.Guid
write-host -nonewline "`n`tThe SPN username is: " -ForegroundColor Yellow; `
write-host -nonewline $app.ApplicationId.Guid`n -ForegroundColor Green; `
write-host -nonewline "`n`tThe Password is: " -ForegroundColor Yellow; `
write-host -nonewline $Password"`n" -ForegroundColor Green; `
write-host -nonewline "`n`tThe Subscription Name is: " -ForegroundColor Yellow; `
write-host -nonewline $Subscription.SubscriptionName"`n" -ForegroundColor Green; `
write-host -nonewline "`n`tThe Subscription Tenant ID is: " -ForegroundColor Yellow; `
write-host -nonewline $Subscription.TenantId`n"`n" -ForegroundColor Green;
}
##########################################################################################
############################## Logon to Azure Tenant ##############################
########################## ...and Setup Service Principal ###########################
##########################################################################################
#region Logon to an Azure environment | @marckean
Write-Host "`nEnter credentials for the Azure Tenant.`n" -ForegroundColor Cyan
$MigrationAzure = Get-AzureRmEnvironment 'AzureCloud'
$MigrationEnv = Login-AzureRmAccount -Environment $MigrationAzure -Verbose
Select-AzureRmProfile -Profile $MigrationEnv
$MigrationSubscription = (Get-AzureRmSubscription | Out-GridView -Title "Choose aan Azure Subscription ..." -PassThru)
Get-AzureRmSubscription -SubscriptionId $MigrationSubscription.SubscriptionId | Select-AzureRmSubscription
SPN-Removal $DisplayName
SPN-Creation $MigrationSubscription $DisplayName $Domain $Password
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment