Autopilot Device Preparation – Add Service Principal

Whilst looking at the docs for Autopilot Device Preparation, I spotted an error on the page for creating the device group:

https://learn.microsoft.com/en-us/autopilot/device-preparation/tutorial/user-driven/entra-join-device-group#create-a-device-group

The instructions for the missing Service Principal use the AzureAD module which is now deprecated.

I’ve created a pull request to get the official page updated, but in the meantime, if you want to use the proper Graph SDK approach, this is what you need to do:

First, this is the PowerShell module:

install-module Microsoft.Graph.Applications

Then import it

import-module Microsoft.Graph.Applications

At this point we could just add the Enterprise App, but if you’re deploying this multiple times, it’s easier to have something repeatable which can be run on tenants both with and without it so lets add some checks first.

$spid = "f1346770-5b25-470b-88bd-d5744ab7952c"
write-output "Checking if Enterprise App exists"
$lookforsp = get-mgserviceprincipal -filter "AppID eq '$spid'"
Now simply check if it exists, if it doesn’t, create it
if (!$lookforsp) {
    write-output "Enterprise App does not exist, creating"
    $ServicePrincipalId = @{
        "AppId" = "$spid"
    }
   $appregid = New-MgServicePrincipal -BodyParameter $ServicePrincipalId
    write-output "Enterprise App created"
}
Whilst you’re in Graph, you could just create the group as well and set the owner on it:
##Get app ID
Write-Output "Getting App ID"
if ($lookforsp) {
    $ownerid = $lookforsp.id
}
else {
    $ownerid = $appregid.id
}
write-output "App ID is $ownerid"
##Create device group
write-output "Creating Device Group"
$groupuri = "https://graph.microsoft.com/beta/groups"
$groupjson = @"
{
    "description": "Autopilot DevicePrep Group",
    "displayName": "$DisplayName",
    "mailEnabled": false,
    "mailNickname": "$DisplayName",
    "securityEnabled": true
}
"@
$group = Invoke-MgGraphRequest -Uri $groupuri -Method Post -Body $groupjson -ContentType "application/json" -OutputType PSObject
$groupid = $group.id
write-output "Device Group Created"
##Set owner
write-output "Setting Owner"
$owneruri = "https://graph.microsoft.com/beta/groups/$groupid/owners/`$ref"
$ownerjson = @"
{
    "@odata.id": "https://graph.microsoft.com/beta/directoryObjects/$ownerid"
}
"@
Invoke-MgGraphRequest -uri $owneruri -Method Post -Body $ownerjson -ContentType "application/json" -OutputType PSObject
write-output "Owner set"

Quick, but hopefully useful!

Leave a Comment