Skip to content

Instantly share code, notes, and snippets.

@joerodgers
Created November 25, 2019 19:21
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 joerodgers/82c113eb6c461be740303cfe28466938 to your computer and use it in GitHub Desktop.
Save joerodgers/82c113eb6c461be740303cfe28466938 to your computer and use it in GitHub Desktop.
Mimics the domain group lookup process used in SharePoint 2016's "Check Permissions" feature.
function Get-PrincipalGroupMembership
{
[CmdletBinding()]
param
(
[parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$Login
)
begin
{
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$username = $domain = $null
}
process
{
if( $login -match "\\" )
{
$chunks = $Login -split "\\"
$domain = $chunks[0]
$username = $chunks[1]
}
elseif($Login -match "@" )
{
$chunks = $Login -split "@"
$domain = $chunks[1]
$username = $chunks[0]
}
else
{
Write-Error "Login must must be in DOMAIN\USERNAME or USERNAME@DOMAIN format"
return
}
$principalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext( [System.DirectoryServices.AccountManagement.ContextType]::Domain, $domain )
$princpial = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity( $principalContext, [System.DirectoryServices.AccountManagement.IdentityType]::SamAccountName, $username)
if( $princpial -ne $null )
{
$directoryEntry = $princpial.GetUnderlyingObject()
$directoryEntry.RefreshCache("tokenGroups") # tag_a3umm
$groupSids = $directoryEntry.Properties["tokenGroups"]
if( $groupSids )
{
foreach( $groupSid in $groupSids )
{
$securityIdentifier = New-Object System.Security.Principal.SecurityIdentifier($groupSid, 0)
[System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($principalContext, [System.DirectoryServices.AccountManagement.IdentityType]::Sid, $securityIdentifier)
}
}
else
{
Write-Error "Failed to find groups for $username. $env:USERNAME must have 'Read remote access information' to read a user's token groups."
}
}
else
{
Write-Error "Failed to find user '$username' in domain '$domain'"
}
}
end
{
}
}
Get-PrincipalGroupMembership -Login "contoso.com\adamb" | FT Sid, SamAccountName, DistinguishedName -AutoSize
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment