Delete Stale Devices in AzureAD with Microsoft.Graph PowerShell
Hi All,
While checking the Devices in my M365 Tenant i was stumbled over the Stale Devices.

The List shows Devices that have an acivity more than 6 Months ago

Let's check if we can get that Information with Microsoft.Graph PowerShell
Connect-MgGraph -Scopes Directory.ReadWrite.All, Directory.AccessAsUser.All
Get-MgDevice
Get-MgDevice

Now we need to get the Devices that are older than six Months
$Devices = Get-MgDevice
$Devices | where {$_.ApproximateLastSignInDateTime -lt (Get-Date).AddMonths(-6)}
$Devices | where {$_.ApproximateLastSignInDateTime -lt (Get-Date).AddMonths(-6)}

We can format that a little better
$Devices | where {$_.ApproximateLastSignInDateTime -lt (Get-Date).AddMonths(-6)} | ft DisplayName,AccountEnabled,OperatingSystem,OperatingSystemVersion,ProfileType,IsManaged,IsCompliant,OnPremisesSyncEnabled,ApproximateLastSignInDateTime

Let's remove these Devices
$StaleDevices = $Devices | where {$_.ApproximateLastSignInDateTime -lt (Get-Date).AddMonths(-6)}
Foreach ($StaleDevice in $StaleDevices)
{
Write-Host "DisplayName: $($StaleDevice.DisplayName) ApproximateLastSignInDateTime: $($StaleDevice.ApproximateLastSignInDateTime)"
$DeviceId = $StaleDevice.Id
Write-Host "Delete Id: $DeviceId" -ForegroundColor Yellow
Remove-MgDevice -DeviceId $DeviceId
}
Foreach ($StaleDevice in $StaleDevices)
{
Write-Host "DisplayName: $($StaleDevice.DisplayName) ApproximateLastSignInDateTime: $($StaleDevice.ApproximateLastSignInDateTime)"
$DeviceId = $StaleDevice.Id
Write-Host "Delete Id: $DeviceId" -ForegroundColor Yellow
Remove-MgDevice -DeviceId $DeviceId
}

These Devices have now been gone

Microsoft Graph Delete device
Sadly there exists no "Application" Permission. This would enable to run a Sheduled Script or a Script in Azure Automation to handle such a Task.

Regards
Andres Bohren
