查询特定用户ID所属本地组:优化现有PowerShell脚本需求
Find Target User's Local Groups on Remote Computers
Got it, let's adjust your PowerShell script to zero in on only the local groups a specific target user belongs to, instead of listing every local group and all their members. Here's the refined version:
# Define your target username and list of computers $TargetUser = "JohnDoe" # Replace with your actual target username $Computername = @("PC01", "PC02", "PC03") # Replace with your list of computers ForEach ($Computer in $Computername) { try { # Connect to the remote computer's WinNT namespace [ADSI]$computerADSI = "WinNT://$computer" # Get all local groups on the computer $localGroups = $computerADSI.children.where({$_.class -eq 'group'}) # Check each group to see if the target user is a member foreach ($group in $localGroups) { [ADSI]$groupADSI = "$($group.Parent)/$($group.Name),group" $members = $groupADSI.psbase.Invoke("Members") # Check if any member matches the target user $isMember = $members | ForEach-Object { $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) } | Where-Object { $_ -eq $TargetUser } if ($isMember) { [PSCustomObject]@{ ComputerName = $Computer GroupName = $group.Name.Value TargetUser = $TargetUser } } } } catch { Write-Warning "Could not connect to $Computer : $_" } }
Key Changes & Notes:
- Target User Focus: We start by defining
$TargetUserso the script knows exactly which account to look for. - Error Handling: Added a
try/catchblock to gracefully handle cases where a computer is offline or inaccessible. - Filter Logic: Instead of outputting every group, we only return groups where the target user is confirmed as a member.
- Clean Output: Uses
PSCustomObjectto structure results clearly with ComputerName, GroupName, and TargetUser columns.
How to Use:
- Replace
$TargetUserwith the username you want to check (e.g., "JaneSmith"). - Update
$Computernamewith your list of target computers (can be a single computer name, too). - Run the script—you'll get a neat list of all local groups the user belongs to across each accessible computer.
内容的提问来源于stack exchange,提问作者RytisM
相关产品推荐
相关产品推荐

