-
-
Save thenikk/1cda34a760578238be27c694ca42470c to your computer and use it in GitHub Desktop.
Autopilotcleanup
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Requires -Modules Microsoft.Graph.Beta.DeviceManagement.Enrollment | |
# Import required module | |
Import-Module Microsoft.Graph.Beta.DeviceManagement.Enrollment | |
# Connect to MgGraph with permission scopes | |
Connect-MgGraph -NoWelcome -Scopes "DeviceManagementServiceConfig.Read.All, DeviceManagementServiceConfig.ReadWrite.All" | |
# Specify time range | |
$currentTime = Get-Date | |
$minAge = $currentTime.AddDays(-365) | |
# Query Microsoft Graph Endpoints and filter for conditions | |
$allAutopilot = Get-MgBetaDeviceManagementWindowsAutopilotDeviceIdentity -All | |
$staleAutopilot = Get-MgBetaDeviceManagementWindowsAutopilotDeviceIdentity -All | Where-Object { $_.EnrollmentState -ne "notContacted" -and $_.LastContactedDateTime -lt $minAge } | |
$neverContactedAutopilot = Get-MgBetaDeviceManagementWindowsAutopilotDeviceIdentity -All | Where-Object { $_.EnrollmentState -eq "notContacted" } | |
Write-Output "$($allAutopilot.Count) Autopilot identities are existing in your tenant." | |
Write-Output "$($staleAutopilot.Count) Autopilot identities have not contacted the Intune service since $($minAge)." | |
Write-Output "$($neverContactedAutopilot.Count) Autopilot identities have not contacted the Intune service ever." | |
# Delete stale devices !On your own responsibility - no liability! | |
foreach ($device in $staleAutopilot) { | |
Write-Output "The device with the following serial number is deleted: $($device.SerialNumber)" | |
# <- Remove hashtag, if deletion is wanted -> # Remove-MgBetaDeviceManagementWindowsAutopilotDeviceIdentity -WindowsAutopilotDeviceIdentityId $device.Id | |
} | |
# Sync Autopilot devices (recommended after deletion), requires module Microsoft.Graph.Beta.DeviceManagement.Actions | |
Sync-MgBetaDeviceManagementWindowsAutopilotSetting |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment