任何依赖 Get-AD___ 的东西都需要 RSAT 工具来获取 ActiveDirectory 模块,这对于作为 @Rohin Sidharth cmets 的最终用户工作站来说是不太可能的假设。
@James C. 目前接受的答案不会处理递归组成员身份(需要 -Recursive 参数),但还涉及列出两个组的所有成员 - 想象一下,如果每个组有十亿个成员 -并且有数组加法的不良习惯。
@Bacon Bits 回答获取用户的组成员身份,这对于“获取更少的数据”更好,但仍然不会处理递归组成员身份,并且仍然依赖于 ActiveDirectory 模块。
为避免 RSAT,可以使用 ADSI 之类的东西 - 它由 System.DirectoryServices.AccountManagement 包装。 Richard Siddaway 讨论了here。
这有一个很好的方法来列出用户的组成员,这似乎被打破了 - 从 Terry Tsay 的 C# 回答类似问题here 中捏出来,我将他的代码移植到这个,但我专注于当前用户和默认包含的通讯组:
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
Function IsUserInGroup([string] $groupName)
{
# Remove DOMAIN\ from the start of the groupName.
$groupName = $groupName -replace '^.*\\'
# Get an AD context for the current user's domain
$context = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList 'Domain', $ENV:USERDOMAIN
# Find the current user account in AD, and refresh the security and distribution groups
$user = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($context, 'SAMAccountName', $env:USERNAME)
$userEntry = [System.DirectoryServices.DirectoryEntry] $user.GetUnderlyingObject()
$userEntry.RefreshCache(@('tokenGroupsGlobalAndUniversal'))
# Get all the security and distribution groups the user belongs to, including nested memberships
$usersGroupSIDs = foreach ($sid in $userEntry.Properties.tokenGroupsGlobalAndUniversal.Value)
{
New-Object System.Security.Principal.SecurityIdentifier -ArgumentList $sid, 0
}
# Get the AD details for the group to test, and test membership
$group = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($context, 'SamAccountName', $groupName)
$usersGroupSIDs.Contains($group.Sid)
}
例如
PS C:\> IsUserInGroup 'parent-nested-group-here'
True
这不是精简或简单的,但它应该以更少的 AD 连接开销来处理更多的条件,尤其是当组的成员数量增加时,并且对额外模块的需求更少,只需使用 .Net 框架。
然后你可以修改它来做
$group2 = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($context, 'SamAccountName', $group2Name)
$usersGroupSIDs.Contains($group.Sid) -or $usersGroupSIDs.Contains($group2.Sid)