Pete Hinchley: Using PowerShell to Find the Group Membership of the Logged On User and Local Computer

Here are two small PowerShell scripts. The first returns the Active Directory group membership of the currently logged on user (i.e. the user running the script). The second returns the Active Directory group membership of the local computer.

In both scripts, the group names are added to an array named $groups (with each group recorded in the form domain\group).

The code for retrieving the group membership of the logged on user:

try {
  $groups = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).Groups | %{
    $_.Translate([System.Security.Principal.NTAccount])
  } | Sort) -join "`r`n"
} catch { "Groups could not be retrieved." }

$groups

The code for retrieving the group membership of the local computer:

$search = New-Object DirectoryServices.DirectorySearcher
$search.SearchRoot = 'LDAP://DC={0}' -f ($env:USERDNSDOMAIN -replace '\.', ',DC=')
$search.Filter = "(&(objectcategory=computer)(cn=$($env:COMPUTERNAME)))"

try {
  $entry = $search.FindOne().GetDirectoryEntry()
  $entry.psbase.RefreshCache('tokenGroups')

  $groups = @()

  $entry.tokenGroups | %{
    $sid = New-Object System.Security.Principal.SecurityIdentifier $_, 0
    $groups += $sid.Translate([System.Security.Principal.NTAccount]).Value
  }
} catch {
  "Groups could not be retrieved."
}

$groups