Skip to content

Instantly share code, notes, and snippets.

@tylerapplebaum
Last active January 3, 2018 18:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tylerapplebaum/3c781e2c4ef4dec3a647bc9c6567bf2f to your computer and use it in GitHub Desktop.
Save tylerapplebaum/3c781e2c4ef4dec3a647bc9c6567bf2f to your computer and use it in GitHub Desktop.
Enumerate user groups
Function Get-UserGroups {
<#
.EXAMPLE
PS C:\> Get-UserGroups -GroupName "Domain Admins"
.EXAMPLE
PS C:\> [bool](Get-UserGroups -GroupName "Domain")
.EXAMPLE
PS C:\> Get-UserGroups -UserName elliot.alderson@e-corp-usa.com
#>
[CmdletBinding()]
param(
[Parameter(HelpMessage="Group name to search for")]
[string]$GroupName,
[Parameter(HelpMessage="User name to search for; other than the currently logged-in user")]
[string]$UserName = "$env:Username@$env:UserDNSDomain"
)
$ErrorActionPreference = "Stop"
$UserGroupArr = New-Object System.Collections.ArrayList #Initialize the ArrayList
Try {
$UserClaims = [Security.Principal.WindowsIdentity]::New($UserName).Claims | Select-Object -First 1
}
Catch [System.Security.SecurityException] {
Write-Error "$($_.Exception.Message)"
}
ForEach ($Claim in @($UserClaims.Subject.Groups)){
$UserGroupObjProperties = @{
"GroupName" = $Claim.Translate([System.Security.Principal.NTAccount]).Value
"SID" = $Claim.Value
}
$UserGroupObj = New-Object PSObject -Property $UserGroupObjProperties
[void]$UserGroupArr.Add($UserGroupObj)
}
$UserGroupArr -match $GroupName
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment