Find Local Group Members

by Jul 25, 2011

If you'd like to list all members of local groups, encapsulate net.exe and make it a PowerShell function:

function Get-LocalGroupMember{
  param(
  [Parameter(Mandatory=$true)]
  $name
  )
  try {
    $ErrorActionPreference = 'Stop'
    $users = net localgroup $name 2>&1
    $users[6..($users.count-3)] -split '\s+' | Where-Object { $_ }
  }
  catch {
    $errmsg =  $_
    if ($errmsg -match '\b(\d{1,8})\b') {
      $errmsg = net helpmsg ($matches[1])
    }
    Write-Warning "Get-LocalGroupMember : $errmsg"
  }
}

Note how the function receives native error messages by redirecting the error to the input channel (2>&1). The catch block then uses a regular expression to check for an error number, and if one exists, it translates the error number to an actually meaningful error text using net helpmsg. So when you submit a local group that does not exist, you get back a meaningful warning instead of some cryptic error code:

PS > Get-LocalGroupMember admin
WARNING: Get-LocalGroupMember :  The specified local group does not exist.

 

Twitter This Tip!
ReTweet this Tip!