PowerShell脚本校验AD用户组归属问题求助:多组场景结果异常
Fixing Your PowerShell Group Membership Check Script
Let's break down why your script isn't working as expected with multiple groups, then fix it to get the output you want.
What's Going Wrong
- Variable Name Collision: You're using
$UserListboth as your input array and your loop variable (foreach ($UserList in $UserList)). This overwrites the original array halfway through the loop, causing unexpected behavior. - Incorrect
-containsUsage: The-containsoperator checks if a single value exists in an array. When you pass$GroupList(an array) to it, it only checks if the last element of$GroupListis present in the user's groups—hence why only the last group shows up asTrue.
The Fixed Script
Here's the revised code that will list all matching groups or False if none are found:
# Load user and group lists from files $UserList = Get-Content "C:\users.txt" $GroupList = Get-Content "C:\Groups.txt" # Initialize an empty array to store results $result = @() foreach ($user in $UserList) { # Use a distinct loop variable to avoid overwriting the array # Fetch the user's AD details $adUser = Get-ADUser $user -Properties SamAccountName, GivenName, Surname # Get all groups the user is a member of (just the SamAccountName) $userGroups = (Get-ADPrincipalGroupMembership -Identity $user).SamAccountName # Find groups that exist in both the user's groups and your target GroupList $matchedGroups = $userGroups | Where-Object { $GroupList -contains $_ } # Set the Groups value: show matched groups joined by commas, or False if none $groupsOutput = if ($matchedGroups.Count -gt 0) { $matchedGroups -join ", " } else { $false } # Build the result object with the Groups field $data = $adUser | Select-Object SamAccountName, GivenName, Surname, @{Name = "Groups"; Expression = { $groupsOutput } } $result += $data } # Print the final results $result
Key Improvements
- Fixed Variable Conflict: Using
$useras the loop variable keeps your original$UserListintact. - Accurate Group Matching: Instead of checking for a single value, we filter the user's groups to find all matches in your
GroupList. - Desired Output Format: The script now outputs a comma-separated list of matched groups, or
Falsewhen there are no matches—exactly like your example.
Optional Performance Boost
If you're working with a large list of groups, converting $GroupList to a hash set will speed up the matching process significantly:
# Convert GroupList to a hash set for faster lookups $GroupSet = [System.Collections.Generic.HashSet[string]]$GroupList # Then replace the Where-Object line with: $matchedGroups = $userGroups | Where-Object { $GroupSet.Contains($_) }
内容的提问来源于stack exchange,提问作者FuriousFamous
相关产品推荐
相关产品推荐

