I wrote the following script last year, was very handy and proved useful for last few Azure projects. The script creates an Azure AD Application, an Azure AD Service Principal and then assign a given role.
<#
.SYNOPSIS
Create Azure AD Service Principal and Assign a role.
.DESCRIPTION
Create an Azure AD Application, an Azure AD Service Principal and then assign a given role.
.NOTES
File Name : CreateAzureADPrincipalAndRole.ps1
Author : Nilay Parikh
Version : 0.1
.PARAMETER RMADAppDisplayName
Specifies the new display name for the application.
.PARAMETER RMADAppHomepage
Specifies the new URL of the application homepage.
.PARAMETER RMADAppIdenfierUris
Specifies the new URIs that identify the application.
.PARAMETER RmADAppPassword
Specifies the password to be associated with the application.
.PARAMETER RmRoleDefinitionName
Name of the RBAC role that needs to be assigned to the principal i.e. Reader, Contributor, Virtual Network Administrator, etc.
#>
[CmdletBinding()]
Param(
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$RMADAppDisplayName,
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$RMADAppHomepage,
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$RMADAppIdenfierUris,
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$RmADAppPassword,
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$RmRoleDefinitionName
)
# Login to Azure
Add-AzureRmAccount
# Create an App
$app = New-AzureRmADApplication -DisplayName $RMADAppDisplayName -HomePage $RMADAppHomepage -IdentifierUris $RMADAppIdenfierUris -Password $RmADAppPassword
$applicationID = $app.ApplicationId.Guid | clip
# App Service Principal
New-AzureRmADServicePrincipal -ApplicationId $app.ApplicationId
#Wait
Start-Sleep 10
# Assign Role DevTest Labs User
New-AzureRmRoleAssignment -RoleDefinitionName $RmRoleDefinitionName -ServicePrincipalName $app.ApplicationId