Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Thursday, April 28, 2011

Enumerate Members of local groups in PowerShell

Here is another script from my last PowerShell class.  After we took a look at the script to enumerate the users who had User Rights assigned to them on a server, one the delegates in class asked if it was possible to enumerate the local users in local groups.  I had to resort to some PowerShell V1 tactics, but it works.  I also got a little help from Steve Schofield’s blog.

<#
===========================================================
Script Name: LocalGroups.ps1
Author: Jason A. Yoder, MCT
Website: WWW.MCTExpert.com
Blogsite: WWW.MCTExpert.Blogspot.com
-----------------------------------------------------------
Script Purpose:
Enumerate the local user accounts that are members
of local groups
-----------------------------------------------------------
Variables:

$GroupList : Holds the names of all the groups on the
             client.

$StrComputer : Used to store the name of the client to
               run this script on.  The "." means the
               local client.

$GL : Used to help cycle through the collection
      $Group List.
     
$Members : A collections of all the members of a group.              
===========================================================
#>
# =========================================================
# Main Code:
Set-StrictMode -version 2.0

# Enumerate the local groups on the client.
$GroupList = Get-WmiObject Win32_Group | ForEach {$_.name}
$strComputer = "."

# Cycle through each group and enumerate the
# Group members.
ForEach ($GL in $GroupList)
{
    $computer = [ADSI]("WinNT://" + $strComputer + `
    ",computer")
    $Group = $computer.psbase.children.find($GL)
    $members= $Group.psbase.invoke("Members") |
    %{$_.GetType().InvokeMember("Name", 'GetProperty', `
    $null, $_, $null)}


    # Display the group and its members.
    Write-Host "Group Name: $GL"
    ForEach($user in $members){Write-Host $user}
    Write-Host "------------------------------------------"
}
# == End of Main Code =====================================

No comments: