任何依靠Get-AD___
需要RSAT工具才能獲得ActiveDirectory模塊,對於最終用戶工作站來說這是不太可能的假設,正如@Rohin Sidharth所評論的。
@詹姆斯C.目前接受的答案不會處理遞歸組成員(需要參數-Recursive
),但也包括列出兩個組的所有成員 - 想象一下,如果每個組的成員數爲十億 - 並且它有陣列增加的不良習慣。
@Bacon位答案獲取用戶的組成員資格,這對於'獲取更少的數據'更好,但仍然不會處理遞歸組成員資格,仍然依賴於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)
}
eg
PS C:\> IsUserInGroup 'parent-nested-group-here'
True
這是不凝結或者更簡單,但它應該用更少的開銷AD連接尤其是作爲組成員的增加數,以及額外的模塊不太需要,只是使用.NET Framework處理更多的條件。
然後,你可以修改,這樣做
$group2 = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($context, 'SamAccountName', $group2Name)
$usersGroupSIDs.Contains($group.Sid) -or $usersGroupSIDs.Contains($group2.Sid)
我正在投票結束這個問題作爲題外話,因爲工作代碼是脫離主題,並且SE網站審查/建議對工作代碼的更改是https://codereview.stackexchange.com/ – TessellatingHeckler
您還假設最終用戶的計算機將安裝AD模塊。如果您將其設計爲登錄腳本,您將遇到該問題。 –