You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

查询特定用户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 $TargetUser so the script knows exactly which account to look for.
  • Error Handling: Added a try/catch block 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 PSCustomObject to structure results clearly with ComputerName, GroupName, and TargetUser columns.

How to Use:

  1. Replace $TargetUser with the username you want to check (e.g., "JaneSmith").
  2. Update $Computername with your list of target computers (can be a single computer name, too).
  3. Run the script—you'll get a neat list of all local groups the user belongs to across each accessible computer.

内容的提问来源于stack exchange,提问作者RytisM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:16:53