Created
May 23, 2018 14:23
-
-
Save gravejester/d95f786d199b9ad747b43d3f73838632 to your computer and use it in GitHub Desktop.
This file contains hidden or 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-ADUserTokenGroups { | |
[CmdletBinding()] | |
param ( | |
[Parameter(Position = 0, ValueFromPipeline)] | |
[ValidateNotNullOrEmpty()] | |
[Alias('u','User')] | |
[string] $ADUserName = $env:USERNAME | |
) | |
try { | |
Add-Type -AssemblyName System.DirectoryServices.AccountManagement | |
$contextType = [System.DirectoryServices.AccountManagement.ContextType]::Domain | |
$principalContext = [System.DirectoryServices.AccountManagement.PrincipalContext]::new($contextType) | |
$userPrincipal = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($principalContext, [System.DirectoryServices.AccountManagement.IdentityType]::SamAccountName,$ADUserName) | |
$userPath = ($userPrincipal.GetUnderlyingObject()).Path | |
$user = [ADSI]"$($userPath)" | |
$user.psbase.refreshCache(@("TokenGroups")) | |
$irc = [System.Security.Principal.IdentityReferenceCollection]::new() | |
foreach($sidByte in $user.TokenGroups) { | |
$irc.Add((new-object System.Security.Principal.SecurityIdentifier $sidByte,0)) | |
} | |
Write-Output ($irc.Translate([System.Security.Principal.NTAccount])) | |
} | |
catch { | |
Write-Warning $_.Exception.Message | |
} | |
} | |
function Test-ADIsMemberOf { | |
[CmdletBinding()] | |
param ( | |
[Parameter(Position = 0)] | |
[ValidateNotNullOrEmpty()] | |
[Alias('u','User')] | |
[string] $ADUserName = $env:USERNAME, | |
[Parameter(Position = 1)] | |
[ValidateNotNullOrEmpty()] | |
[Alias('g','Group')] | |
[string] $ADGroupName = 'BUILTIN\Users' | |
) | |
try { | |
Write-Verbose "Testing if $($ADUserName) is a member of a group named '$($ADGroupName)'" | |
$tokenGroups = Get-ADUserTokenGroups -ADUserName $ADUserName | |
Write-Output ([bool]($tokenGroups.where({$_.Value -eq $ADGroupName}))) | |
} | |
catch { | |
Write-Warning $_.Exception.Message | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment