检查用户是否是AD群组列表的成员

时间:2017-09-19 08:22:17

标签: powershell active-directory quest

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

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

我搜索过很多东西,找不到任何东西,也许我在Google搜索中太糟糕了:)。

$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 in group_name

2 个答案:

答案 0 :(得分:0)

问题是为什么在循环结果这么简单时你想要使用管道?

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

$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"
        }
    }
}

答案 1 :(得分:0)

如果您的服务器上没有安装Active Directory PowerShell功能,则可以使用此方法。在这里,我正在检查域组是否属于服务器上的本地管理员组,但是如果要检查用户是否属于,则可以将GroupPrincipal更改为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
}