How do not display an error for "Get-MgGroup" or other Graph cmdlets

Mountain Pond 1,281 Reputation points


I'm using "Get-MgGroup" from the MS Graph module.

I understand that we cannot use -ErrorAction with this cmdlet.

However, for some reason "Get-MgUserMemberOf" returns a list that contains a non-existent group (that's another question). I cannot find this group and further processing of the list using Get-MgGroup returns an error.

This doesn't look very good and I would ignore this error in the script. However, it arises all the time.

Question. How to suppress error output.

Thank you.



$GroupMembership = Get-MgUserMemberOf -UserId $UPN -All

FOREACH ($ID in ${
    $TargetGroup = Get-MgGroup -GroupId $ID -ErrorVariable MyError
} CATCH {}

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,783 questions
0 comments No comments
{count} votes

Accepted answer
  1. Vasil Michev 96,676 Reputation points MVP

    The Get-MgUserMemberOf cmdlet does not only return Group objects, but Directory role and Administrative units as well. So this is not an issue with "non-existing group", but rather using the incorrect cmdlet to resolve the GUID.

    If you expand the properties of the objects stored within your GroupMembership variable, you will be able to see what type of object is returned. Alternatively, if you only want to fetch actual groups, you can use this:

    Get-MgUserMemberOf -UserId $UPN -All:$true | ? {$_.AdditionalProperties.'@odata.type' -eq ""}

    You can also do the filter server-side, but the Graph PowerShell module does very bad at handling the output for that scenario, so I'll skip the example.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful