Azure, Microsoft

Create Azure AD Account and Assign Role

Summary

Create Azure Active Directory user account and assign role with PowerShell.

Prerequisite

Install Azure PowerShell

Deploy

#Load modules and connect to AzureAD
Install-Module AzureAD
Import-Module AzureAD
Connect-AzureAD -TenantId <Enter Tenant ID Here>

$DisplayName = "Santa Claus"
$FirstName = "Santa"
$LastName = "Claus"
$Email = "santaclaus@derrickpark.com"
$NickName = "santaclaus"
$Password = "ChangeMe#1234"

#Create AAD account
$PasswordProfile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$PasswordProfile.Password = $Password
New-AzureADUser -DisplayName $DisplayName -GivenName $FirstName -SurName $LastName -UserPrincipalName $Email -UsageLocation US -MailNickName $NickName -PasswordProfile $PasswordProfile -AccountEnabled $true

#Assign role to user
$userName = $Email 
$roleName = "Company Administrator"
$role = Get-AzureADDirectoryRole | Where {$_.displayName -eq $roleName}
if ($role -eq $null) {
$roleTemplate = Get-AzureADDirectoryRoleTemplate | Where {$_.displayName -eq $roleName}
Enable-AzureADDirectoryRole -RoleTemplateId $roleTemplate.ObjectId
$role = Get-AzureADDirectoryRole | Where {$_.displayName -eq $roleName}
}
Add-AzureADDirectoryRoleMember -ObjectId $role.ObjectId -RefObjectId (Get-AzureADUser | Where {$_.UserPrincipalName -eq $userName}).ObjectID

Leave a Reply

Your email address will not be published. Required fields are marked *

Close Bitnami banner
Bitnami