Anything which relies on Get-AD___
needs the RSAT tools to get the ActiveDirectory module, that's an unlikely assumption for end user workstations as @Rohin Sidharth comments.
@James C.'s currently accepted answer will not handle recursive group membership (would need the -Recursive
parameter), but also involves listing all the members of both groups - imagine if that was a billion members for each group - and it has the poor habit of array addition.
@Bacon Bits answer gets the user's group membership which is better for 'getting less data' but still won't handle recursive group membership and still relies on the ActiveDirectory module.
To avoid RSAT, something like ADSI could be used - which is wrapped by System.DirectoryServices.AccountManagement. Discussed here by Richard Siddaway.
That has a nice method to list the group members for a user, which appears to be broken - pinching from Terry Tsay's C# answer on a similar question here, I port his code to this but I've focused on the current user and included distribution groups by default:
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
Function IsUserInGroup([string] $groupName)
{
# Remove DOMAIN\ from the start of the groupName.
$groupName = $groupName -replace '^.*\\'
# Get an AD context for the current user's domain
$context = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList 'Domain', $ENV:USERDOMAIN
# Find the current user account in AD, and refresh the security and distribution groups
$user = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($context, 'SAMAccountName', $env:USERNAME)
$userEntry = [System.DirectoryServices.DirectoryEntry] $user.GetUnderlyingObject()
$userEntry.RefreshCache(@('tokenGroupsGlobalAndUniversal'))
# Get all the security and distribution groups the user belongs to, including nested memberships
$usersGroupSIDs = foreach ($sid in $userEntry.Properties.tokenGroupsGlobalAndUniversal.Value)
{
New-Object System.Security.Principal.SecurityIdentifier -ArgumentList $sid, 0
}
# Get the AD details for the group to test, and test membership
$group = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($context, 'SamAccountName', $groupName)
$usersGroupSIDs.Contains($group.Sid)
}
e.g.
PS C:\> IsUserInGroup 'parent-nested-group-here'
True
Which isn't condensed or simpler, but it should handle more conditions with less AD connecting overhead especially as member count of groups increases, and less need for extra modules, just using the .Net framework.
Then you could modify that to do
$group2 = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($context, 'SamAccountName', $group2Name)
$usersGroupSIDs.Contains($group.Sid) -or $usersGroupSIDs.Contains($group2.Sid)