I'm looking to check current user group membership and run the script based on that. This script runs. However, it requires RSAT Active Directory tools to run.
I would like to run this script as a GPO. Does anyone have any ideas?
Thanks in advance.
###########################################################################################
# Check AD group Membership
###########################################################################################
$user = "$env:UserName"
$groups = 'FM-TMASQLUserAccess'
foreach ($group in $groups) {
$members = Get-ADGroupMember -server **servernamehere** -Identity $group -
Recursive | Select -ExpandProperty SamAccountName
If ($members -contains $user) {
Write-Output "$user is a member of $group"
}
Else {
Write-Output "$user is not a member of $group"
}
}
Mathias R. Jessen
178k13 gold badges175 silver badges234 bronze badges
1 Answer 1
For the current logged in user, specifically, you don't need to explicitly query AD - the users security token already contains all the group memberships resolved at logon, so you can do:
$groupName = 'FM-TMASQLUserAccess'
# Fetch identity information about current user
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
# Grab group SIDs from the users token
$groupTokenSIDs = $currentUser.Groups
# Translate the SID references to account/group names
$Groups = $groupTokenSIDs |Where-Object { $_.AccountDomainSid } |ForEach-Object { $_.Translate([System.Security.Principal.NTAccount]) }
# Test if list contains target group
if($Groups |Where-Object { $_.Value -like "*\$groupName" }){
"$env:USERNAME is a member of $groupName"
}
answered Oct 8, 2021 at 12:48
Mathias R. Jessen
178k13 gold badges175 silver badges234 bronze badges
Sign up to request clarification or add additional context in comments.
8 Comments
lit
Does this only return domain groups? How can I find local groups?
Mathias R. Jessen
@lit It returns both local groups, domain groups, and global identifiers/labels - anything already in the users access token. Variable naming was slightly misleading, I've updated the code.
lit
When I run this, the
$Groups variable contains only names prefixed with the AD domain; EAST\ . There is no Administrators or Users group.Bill_Stewart
IMO this code should say
$_.Value in the Where-Object filter that translates the SIDs (rather than $_.AccountDomainSid).Mathias R. Jessen
@Bill_Stewart That's deliberate. OP is interested in a non-builtin AD group, I'm filtering out WKSIDs (like
BUILTIN\Users) - in an attempt to narrow the list without having to resolve the actual domain SID :) |
lang-bash