Created
November 25, 2019 19:21
-
-
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.
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-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