Advanced Windows PowerShell Scripting Video Training

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

Wednesday, January 25, 2012

How to list the members of every Active Directory group with PowerShell

The code will allow you to see every member of every group in Active Directory.  The output is placed in in object so you can process it through the PowerShell pipeline.

# Import the Active Directory Module.

# You must have access to the Active Directory Module for # this code to work.

Import-Module ActiveDirectory -Cmdlet Get-ADGroup, Get-ADGroupMember

# Create an array to hold the objects as they are created.

$Objects = @()

 

# Store the objects of all groups in Active Directory.

$Groups = Get-ADGroup -filter *

 

# Loop through each group and enumerate the user objects # who are members of each group.

ForEach-Object ($G in $Groups)

{

    # Enumerate each member object of the group

    $Members = $G | Get-ADGroupMember

   

    # Loop through each user object and add data

#to the output object.

    ForEach-Object ($M in $Members)

    {

        # Create a new instance of an object.

        $ObjectData = New-Object PSObject

       

        # Add data to the object.

        # The property of "Group" will be the "Name" property of the

        # current group being interrogated.

        $ObjectData | Add-Member NoteProperty -Name "Group" -Value $G.Name

       

        # The property of "User" will be the "Name" property of the

        # current user being interrogated.

        $ObjectData | Add-Member NoteProperty -Name "User" -Value $M.Name

       

        # The property of "GroupType" will be the "GroupCategory" property

        # of the current group being interrogated.

        $ObjectData | Add-Member NoteProperty -Name "GroupType" -Value $G.GroupCategory

       

        # Add this instance to the object.

        $Objects += $ObjectData

    } # -- End: ForEach-Object ($M in $Members)

} # -- End: ForEach-Object ($G in $Groups)

 

# Send to object to the pipeline.

$Objects

No comments: