Remove stale devices from Azure AD using Micrsoft Graph powershell SDK

Sudhish kumar 1 Reputation point
2022-10-27T12:48:12.683+00:00

How can I remove stale devices from Azure AD using MS graph PowerShell module?

Trying with {Device.ReadWrite.All, Directory.ReadWrite.All} scops, even Get-MgDevice show the following error

PS C:\WINDOWS\system32> Get-MgDevice -DeviceId 91140dae-dc4a-4c72-aba2-ea2a391747a9 Get-MgDevice : Resource '91140dae-dc4a-4c7288888' does not exist or one of its queried reference-property
objects are not present.
At line:1 char:1

  • Get-MgDevice -DeviceId 91140dae-dc4a-4c72-aba2-ea2a391747a9
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  • CategoryInfo : InvalidOperation: ({ DeviceId = 91...ndProperty = }:<>f__AnonymousType403) [Get-MgDevi ce_Get1], RestException1
  • FullyQualifiedErrorId : Request_ResourceNotFound,Microsoft.Graph.PowerShell.Cmdlets.GetMgDevice_Get1
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,521 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Romanowicz, Marcin 40 Reputation points
    2023-05-19T14:30:36.5266667+00:00

    OK. I figured it out if anyone is interested:

    # Delete Azure AD devices older than 120 days
    $dt = (Get-Date).AddDays(-120)
    $jt = "Workplace" # Join Type
    
    $Devices = Get-MgDevice -All:$true | Where-Object {($_.ApproximateLastSignInDateTime -le $dt) -and ($_.TrustType -eq $jt)}
    
    foreach ($Device in $Devices) 
        {
        Remove-MgDevice -DeviceId $Device.Id
        }
    
    3 people found this answer helpful.

  2. Vicky Kumar (Mindtree Consulting PVT LTD) 1,156 Reputation points Microsoft Employee
    2022-10-31T05:53:02.27+00:00

    Please follow the doc to manage-stale-devices - https://learn.microsoft.com/en-us/azure/active-directory/devices/manage-stale-devices

    Hope this helps
    Thanks