在Powershell 4.0中从本地组检索本地用户

问题描述 投票:0回答:1

我想从所有本地组中检索所有本地用户。 我可以像这样从服务器计算机的所有组中检索所有用户:

Get-CimInstance -ClassName Win32_GroupUser | Select-Object -Property GroupComponent, PartComponent | fl

但是我想限制为本地用户和组。我知道如果我使用 Win32_GroupWin32_UserAccount ,可以添加 -Filter "LocalAccount='True'" 但我不知道如何为 Win32_GroupUser 执行此操作。 我已经尝试了几件事,我相信我已经不远了,但现在我有点卡住了...... 我的最后一段代码是,但它什么也没返回:

$users=Get-CimInstance -ClassName Win32_UserAccount -Filter "LocalAccount='True'" | Select-Object -Property Name
$groups=Get-CimInstance -ClassName Win32_Group -Filter "LocalAccount='True'" | Select-Object -Property Name
ForEach ($group in $groups) {
    ForEach ($user in $users) {
        Get-CimInstance -ClassName Win32_GroupUser | Where-Object {$_.groupcomponent -match 'Win32_Group.Name="$group"' -and $_.partcomponent -match 'Win32_UserAccount.Name="$user"'} | Select-Object -Property GroupComponent, PartComponent | fl
    }
}

我的最终目标是将此代码放入 Ansible playbook 中并在多个远程服务器中运行它。 如果您知道如何解决这个问题或如何帮助我,我将不胜感激。

powershell ansible active-directory wmi powershell-4.0
1个回答
1
投票

我的最终解决方案:

$groups = Get-CimInstance -ClassName Win32_Group -Filter "LocalAccount='True'" | Select-Object -Property Name
ForEach ($group in $groups) {
    $members = $([ADSI]"WinNT://$($env:COMPUTERNAME)/$($group.Name)").members() | % {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
    ForEach ($member in $members) {
        $local = Get-CimInstance -ClassName Win32_UserAccount -Filter "LocalAccount='True'" | Select-Object -Property Name | Where-Object Name -eq $member
        if ($local) {"This is the local group: $($group.Name) and this is the local account: $($local.Name)"} else {}
    }
}

这提供了一种从本地组中获取本地用户的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.