Get-ADGroup and ErrorAction

Hello,

I would expect

get-adgroup S-1-5-21-842925246-2139871995-725345543-351830 -erroraction silentlycontinue -errorvariable err

To fail silently when SID does not match any existing group

It actually still exposes the stack:

get-adgroup S-1-5-21-842925246-2139871995-725345543-351830 -erroraction silentlycontinue -errorvariable err
get-adgroup : Cannot find an object with identity: 'S-1-5-21-842925246-2139871995-725345543-351830' under:
'DC=xxx,DC=redacted,DC=com'.
At line:1 char:1
+ get-adgroup S-1-5-21-842925246-2139871995-725345543-351830 -erroracti ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (S-1-5-21-842925...25345543-351830:ADGroup) [Get-ADGroup], ADIdentityNot
   FoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,M
   icrosoft.ActiveDirectory.Management.Commands.GetADGroup

Do I need to understand that Get-ADGroup does not respect Common parameters and I absolutely need a try/catch block to hide those ?

If you just need a workaround you can use the parameter `-Filter` instead:

Get-ADGroup -Filter "SID -eq 'S-1-5-21-842925246-2139871995-725345543-351830'"

This will not throw an error if the SID is not found. :wink:

1 Like

It will be better for one-liners, yes !

Remember to include all quotes for Filter:

<list of SID> | % { (Get-ADGroup -Filter "SID -eq '$_'")}

Thank you

I would prefer Microsoft to respect its own best practice for cmldlet management, to be honest, but the Filter trick could be very useful for other commands also.

The AD cmdlets pretty commonly do not behave the same as other cmdlets when changing the ErrorAction preference.
I usually have to wrap my query in Try/Catch blocks

try {
    get-adgroup S-1-5-21-842925246-2139871995-725345543-351830 -erroraction stop -errorvariable err
} catch {
    write-warning "group not found"
}


This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.