4
$groups = 'group1', 'group2'....

我需要检查用户是否在特定的 AD 组中,如果不是,则回显组名;我可以在管道中进行吗?

我用谷歌搜索了很多,但找不到任何东西,也许我在英文谷歌搜索方面太糟糕了:)。

$groups |
    Get-QADGroupMember |
    Get-QADUser -SamAccountName 'lalala' | ForEach-Object {
        if ($_.SamAccountName -ne $null) {
            Write-Host "ok"
        } else {
            Write-Host 'not ok'
        }
    }

我怎样才能显示:not ok. user is not ingroup_name

4

2 回答 2

6

问题是,当循环遍历结果如此简单时,为什么要使用管道?

要检查用户是否是组列表的成员:

$user = "TestUsername"
$groups = 'Domain Users', 'Domain Admins'

foreach ($group in $groups) {
    $members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty SamAccountName

    If ($members -contains $user) {
        Write-Host "$user is a member of $group"
    } Else {
        Write-Host "$user is not a member of $group"
    }
}

对于多个用户:

$users = "TestUsername1", "TestUsername2", "TestUsername3"
$groups = 'Domain Users', 'Domain Admins'

foreach ($user in $users) {
    foreach ($group in $groups) {
        $members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty SamAccountName

        If ($members -contains $user) {
            Write-Host "$user is a member of $group"
        } Else {
            Write-Host "$user is not a member of $group"
        }
    }
}
于 2017-09-19T09:09:24.410 回答
0

如果您的服务器上没有安装 Active Directory PowerShell 功能,您可以使用此方法。在这里,我正在检查域组是否是服务器上本地管理员组的一部分,但如果您想检查用户是否属于某个组,您只需更改GroupPrincipalto并提供用户名即可。UserPrincipal此外,如果该组是域组,则$domainContext对两个FindByIdentity调用都使用 。

function Test-DomainGroupIsMemberOfLocalAdministrators([string] $domainName, [string] $domainGroupName)
{
    Add-Type -AssemblyName 'System.DirectoryServices.AccountManagement'
    $domainContext = [System.DirectoryServices.AccountManagement.PrincipalContext]::new([System.DirectoryServices.AccountManagement.ContextType]::Domain, $domainName)
    $localMachineContext = [System.DirectoryServices.AccountManagement.PrincipalContext]::new([System.DirectoryServices.AccountManagement.ContextType]::Machine)
    $domainGroup = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($domainContext, $domainGroupName)
    $localAdministratorsGroup = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($localMachineContext, "Administrators")

    if($domainGroup -ne $null)
    {
        if ($domainGroup.IsMemberOf($localAdministratorsGroup))
        {
            return $true
        }
    }
    return $false
}
于 2018-05-08T18:10:33.960 回答