Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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


This post first appeared on Hinchley.net, please read the originial post: here

Share the post

Using PowerShell to find the group membership of the logged on user and local computer

×

Subscribe to Hinchley.net

Get updates delivered right to your inbox!

Thank you for your subscription

×