Last active
October 12, 2021 15:49
-
-
Save dpo007/344edeb8d8284e2ab99ce5f4309e595b to your computer and use it in GitHub Desktop.
PowerShell :: Get-ADUserNestedMemberships
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Get-ADUserNestedMemberships { | |
param ( | |
[string]$SAMAccountName = $env:USERNAME | |
) | |
$userNestedMembership = @() | |
$domainConnection = New-Object DirectoryServices.DirectoryEntry | |
$domainConnection.AuthenticationType = [System.DirectoryServices.AuthenticationTypes]::Secure | |
$samSearcher = New-Object System.DirectoryServices.DirectorySearcher | |
$samSearcher.SearchRoot = $domainConnection | |
$samSearcher.Filter = ('(samAccountName={0})' -f $SAMAccountName) | |
$samSearcher.PropertiesToLoad.Add('displayName') | Out-Null | |
$samResult = $samSearcher.FindOne() | |
if ($samResult) | |
{ | |
$theUser = $samResult.GetDirectoryEntry() | |
$theUser.RefreshCache(@('tokenGroups')) | |
foreach ($resultBytes in $theUser.Properties['tokenGroups']) | |
{ | |
$SID = New-Object System.Security.Principal.SecurityIdentifier($resultBytes,0) | |
$sidSearcher = New-Object System.DirectoryServices.DirectorySearcher | |
$sidSearcher.SearchRoot = $domainConnection | |
$sidSearcher.Filter = ('(objectSid={0})' -f $SID.Value) | |
$sidSearcher.PropertiesToLoad.Add('name') | Out-Null | |
$sidResult = $sidSearcher.FindOne() | |
if ($sidResult) | |
{ | |
$userNestedMembership += ([string]$sidResult.Properties['name'][0]) | |
} | |
} | |
} | |
return $userNestedMembership; | |
<# | |
.SYNOPSIS | |
Get list of AD groups user belongs to, directly or indirectly. | |
.DESCRIPTION | |
Get list of AD groups user belongs to, directly or indirectly, without the AD module. Created to replace notoriously slow "GetAuthorizationGroups" from [System.DirectoryServices.AccountManagement.Principal]. | |
.PARAMETER SAMAccountName | |
AD account name of user you wish to look up. Default is current user. | |
.EXAMPLE | |
Get-ADUserNestedMemberships | |
.EXAMPLE | |
Get-ADUserNestedMemberships -SAMAccountName jsmith | |
.LINK | |
Based on C# code found here: https://milestone.topics.it/2012/12/userprincipalgetauthorizationgroupsoh-my.html | |
#> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment