I'm working on a script for Entra device maintenance that checks the last activity of devices. If any device hasn't been active for over 90 days, the script disables it as per management's request. I'm using an Entra app registration with the appropriate Graph permissions, and I can confirm this with Get-MgContext.
I'm running the script in PowerShell 7, but I've also tested it in PowerShell 5 to rule out version issues. Instead of targeting specific devices, I'm using Where-Object for filtering. This filters out AutoPilot devices and hybrids maintained by another script.
Here's the core part of my script:
```powershell
$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 the script interactively, my log indicates that I fetched 330 enabled devices. However, when I run it as a scheduled task under a Managed Service Account, it reports fetching 900 enabled devices instead. I'm baffled as to why the Where-Object conditions seem to be ignored in the scheduled task. I'm also looking for ways to troubleshoot what's happening when operating under an MSA. I heard I can run VS Code as MSA using PSEXEC, but it just exits immediately with no error. Any ideas? I'm really struggling to resolve this issue!
3 Answers
That's a good point about using the filter! I've had the same issue before. Just to clarify, the scheduled task might be running under different permissions or contexts, which could cause it to see more devices. Make sure the MSA has the same access rights as your interactive session.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically