azurepowershellmicrosoft-graph-apisystem-administration

MS Graph Powershell - User with no manager - error


I'm trying to write a script for decommissioning user accounts in EntraID using the MS Graph API.

What I'd like to do, is check for and "handle" any case where the user doesn't have a manager set.

Most of them do, but I've found if there is no manager, I get this odd error.

Get-MgUserManager : Resource 'manager' does not exist or one of its queried reference-property objects are not present.
At line:1 char:7
+ try { $mymanager = Get-MgUserManager -UserId ian.testpw@mycompany. ...
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: ({ UserId = ian....ndProperty =  }:<>f__AnonymousType10`3) [Get-MgUserManager_Get1], RestException`1
    + FullyQualifiedErrorId : Request_ResourceNotFound,Microsoft.Graph.PowerShell.Cmdlets.GetMgUserManager_Get1

I am not an expert coder, but a sys admin with a few years under my belt, but I was expecting to get just a null value returned, that way I could test if there was no manager, and my script would then not bother trying to remove it.

Does anyone have knowledge/experience with this scenario or error. I tried a try,catch for it, but it doesn't seem to catch it.

When I've looked at the $Error variable. the exception is more complex than the usual one you get from powershell and when I tried using that, it failed because there are multiple nested square brackets in the response, which powershell doesn't like.

Any thoughts or suggestions gratefully received.

Tried

$mymanager = Get-MgUserManager -UserId ian.testpw@mycompany.com

was really expecting a Null response


Solution

  • A simple way to avoid the error is to use $expand instead of calling the List manager endpoint (this is the endpoint called by Get-MgUserManager behind the scenes).

    So to summarize, this approach would avoid the error, it will get you the user you're querying and in addition, if the user has a manager assigned, it will also give you a .manager property otherwise this property will not exist:

    $targetUser = 'ian.testpw@mycompany.com'
    $user = Invoke-MgGraphRequest GET "v1.0/users/${targetUser}?`$expand=manager"
    $user.manager # this can be empty or the reference user but no errors
    

    This approach, same endpoint used by the cmdlet, will throw an error if the user does not have a manager assigned:

    $manager = Invoke-MgGraphRequest GET 'v1.0/users/ian.testpw@mycompany.com/manager'
    

    You can use a try / catch here to avoid the error if you want. -ErrorAction SilentlyContinue wouldn't work here as this is a pipeline terminating error.

    $targetUser = 'ian.testpw@mycompany.com'
    $manager = try { Invoke-MgGraphRequest GET "v1.0/users/${targetUser}/manager" } catch { }