If your script needs to know whether the current user is member in a given group, then the fastest and least resource intense approach for this is to use code like this:
$token = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$xy = 'S-1-5-64-36'
if ($token.Groups -contains $xy)
"You're in this group."
The sample would execute code when the current user is direct or indirect member of the group identified by SID S-1-5-64-36 (replace this SID with the SID of any group that matters to you).
This piece of code accesses the access token that a user already exists and always has access to. No time-consuming separate AD queries, and no issues with nested group memberships. The access token features a complete list of direct and indirect groups the current user is member in.
All groups are listed by SID which makes total sense. Resolving SID names again is time consuming and pointless. If you just want to know whether a user is member in a group, then just find out the SID for that group (i.e. by using Get-AdGroup), then use this SID in the approach above.
ReTweet this Tip!
Powered by IDERA