Thursday, 7 July 2011

Powershell: List Local Users & Groups

I recently encountered a permissions issue on SQL Server, the route cause of which was a user being removed from a local windows group on a production server. This got me thinking of yet another use for Powershell, to list out the local users and groups on a particular server.

ListLocalGroupMembership.ps1
$computerName = Read-Host 'Enter computer name or press <Enter> for localhost'  
  
if ($computerName -eq "") {$computerName = "$env:computername"}
$computer
= [ADSI]"WinNT://$computerName,computer"
$groups = $computer.psbase.Children | Where-object { $_.psbase.schemaclassname -eq 'group' }

foreach ($group in $groups)
{
   $users
= $group.psbase.invoke("Members")
  
$group.name
   write
-host "----------------------------------------------------"

  
if ($users -ne $null)
  
{
      
foreach ($user in $users)
      
{
           $user.GetType
().InvokeMember("Name","GetProperty",$null,$user,$null)
      
}
   }
  
else
  
{
       write
-host "-----EMPTY-----" -foreground "red"
  
}

   write
-host "----------------------------------------------------"
  
write-host ""
}


The basis of this script was taken from here.

You could easily take this a stage further and log this data to a repository and then alert any changes made.

1 comment:

  1. thanks for the script! tip for others: you can also do $user.GetType().InvokeMember("adspath","GetProperty",$null,$user,$null) to get the domain part of the username

    ReplyDelete

/* add this crazy stuff in so i can use syntax highlighter