Batch creating privileged access groups in Azure AD

Quick blogpost today, showing how to batch create privileged access groups for the Privileged Identity Management feature in Azure AD. The endpoint used is not currently documented in the Graph documentation.

First thing you need to do is get yourself an access token. Follow my guide for this. This script will use a hardcoded variable for the token.

# Get your access token somehow, not in scope for this example
$accesstoken = "eyJ0eXAiOiJKVGtHUniJSUzI1NiIs--- snip ---wFzrJUYkOm37KY27WJvQ"

# Groups to create
$groups = "test12345","test123468","test9577","test304934089"

# No need to edit below this line

# Build header value
$headers = @{Authorization = "Bearer $accesstoken"}
$groups | Foreach {
    # Check if group already created
    $matching = Invoke-RestMethod "`$filter=displayName eq '$($_)'" -Headers $headers 

    $id = $null
    # Create if no group was found
    if(!$matching.value) {
        Write-Verbose "Creating group: $($_)" -Verbose
        $body = @{
            displayName = $_
            isAssignableToRole = $true
            mailEnabled = $false
            mailNickname = $_
            securityEnabled = $true
        } | ConvertTo-Json

        $creation = Invoke-RestMethod "" -Headers $headers -Method Post -Body $body -ContentType "application/json"
        Write-Verbose "Group '$($_)' created with object id $($" -Verbose
        $id = $
    } else {
        Write-Verbose "Group '$($_)' already created" -Verbose
        $id = $matching.value[0].id

    # Check for PIM registration of group
    $pimmatching = Invoke-RestMethod "`$filter=externalId eq '$id'" -Headers $headers

    # Register group in PIM, if not already registered
    if(!$pimmatching.value) {
        Write-Verbose "Registering group $($_) ($id) in PIM" -Verbose
        $body = @{
            externalId = $id
        } | ConvertTo-Json

        $registration = Invoke-RestMethod "" -Headers $headers -Method Post -Body $body -ContentType "application/json"
    } else {
        Write-Verbose "Group $($_) already registered in PIM" -Verbose

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s