Use paging with Graph to change group tags on all AutoPilot devices. Graph has a 1000 device limit and this script uses paging to get all of the devices. Once we have all of the devices we can manipulate group tags.
I would like to shout out January 2021 – TheSleepyAdmins for the assist on paging as well as Bulk Updating Autopilot enrolled devices with Graph API and assigning a Group Tag based on Purchase OrderID - Systems Management Squad (sysmansquad.com) for help with some of the other bits.
# Application (client) ID, tenant Name and secret
$clientid = Read-Host "Input your Client ID"
$clientSecret = Read-Host "Input Client Secret"
$TenantName = Read-Host "Input Tenant Name"
$resource = "https://graph.microsoft.com/"
#$grouptag = "AP-Tag1"
$ReqTokenBody = @{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
client_Id = $clientID
Client_Secret = $clientSecret
}
$TokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token" -Method POST -Body $ReqTokenBody
$apiUrl = 'https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotDeviceIdentities/'
$Data = Invoke-RestMethod -Headers @{Authorization = "Bearer $($TokenResponse.access_token)"} -Uri $apiUrl -Method Get
$Results = @()
$Results += $Data.value
[int]$pagecount = 0
$Pages = $Data.'@odata.nextLink'
while($null -ne $Pages) {
$pagecount += 1
Write-host "Checking Page $Pagecount. Count is $($Results.count)"
$Addtional = Invoke-RestMethod -Headers @{Authorization = "Bearer $($TokenResponse.access_token)"} -Uri $Pages -Method Get
if ($Pages){
$Pages = $Addtional."@odata.nextLink"
}
$Results += $Addtional.value
}
$Results | Export-Csv -Path "c:\temp\Devices.csv" -NoTypeInformation
#Tag the devices
if($grouptag -ne $null){
$body = '{"groupTag":"'+$groupTag+'"}'
foreach ($Result in $Results) {
$apiUrl = "https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotDeviceIdentities/$device/UpdateDeviceProperties"
$rest = Invoke-RestMethod -Headers @{Authorization = "Bearer $($TokenResponse.access_token)"} -Uri $apiUrl -Body $body -Method Post -ContentType 'application/json'
Write-Host ($device + ' has been added to the ' + $grouptag)
}
#Sync the changes
$apiUrl2 = "https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotSettings/sync"
Invoke-RestMethod -Headers @{Authorization = "Bearer $($TokenResponse.access_token)"} -Uri $apiUrl2 -Method Post
}
No comments:
Post a Comment