Why does Get-MgDevice return different results when run interactively versus as a scheduled task?

0
14
Asked By TechWhiz23 On

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

Answered By PowershellPal On
Answered By CodeCrafter77 On
Answered By ScriptNinja42 On

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.