Skip to content

Instantly share code, notes, and snippets.

@dpo007
Last active October 12, 2021 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpo007/344edeb8d8284e2ab99ce5f4309e595b to your computer and use it in GitHub Desktop.
Save dpo007/344edeb8d8284e2ab99ce5f4309e595b to your computer and use it in GitHub Desktop.
PowerShell :: Get-ADUserNestedMemberships
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