I'm working on a script for managing devices using Entra, specifically to check their last activity. The requirement is to disable any device that's been inactive for over 90 days, as per management's request. I authenticate using an Entra app registration with the correct Graph permissions, and everything checks out with Get-MgContext.
The script runs on PowerShell 7 (I also tested it on version 5, and the outcome is the same). To avoid targeting specific devices, I use Where-Object to filter out AutoPilot objects and hybrid devices. Here's the code snippet I'm using:
`$allEnabledDevices = Get-MgDevice -All -Property * | Where-Object {`
`($_.TrustType -ne "serverAD") -and`
`($_.PhysicalIds -notcontains 'ZTDID') -and`
`($_.ApproximateLastSignInDateTime -ne $null) -and`
`($_.AccountEnabled -eq $true) -and`
`($_.ManagementType -ne "MDM")`
`}`
When I run this interactively, I see the log indicating that 330 enabled devices were fetched. However, when the same script runs as a scheduled task under a Managed Service Account (MSA), it reports that 900 enabled devices were fetched. I'm baffled as to why the WHERE filtering seems to be ignored in the MSA context, and I'm looking for ways to troubleshoot this issue. Any insights would be greatly appreciated!
1 Answer
It sounds like your script might be fetching all devices before the filtering happens, which could explain the different counts. To speed things up and avoid confusion, try using the `-Filter` parameter with your `Get-MgDevice` command. This way, you can filter on the server side instead of fetching everything first. It should simplify your code and enhance performance!
Yeah, I think you'll find that doing it this way makes your life easier once you get the hang of it!

I totally get that formatting makes it harder, but dealing with massive datasets can be a pain. Filtering early can save you a lot of headaches!