Active Directory module PowerShell cmdlets : Part 2

SubSunIT Infrastructure Architect
Exchange Server and Active Directory Expert | PowerShell Enthusiast
This article series will focus on learning Active Directory module PowerShell cmdlets. As I mentioned in part 1, I am going to get you started working on PowerShell right away!!

If you would like to read the other part/s in this article series please go to:
Active Directory module PowerShell cmdlets : Part 1


In the first part of this multi-part series, we looked at how to install and import the Activedirectory Module, how to find the cmdlets and how to get help for a cmdlet. In addition we have seen the common Active Directory cmdlets and learned the usage with examples of Get-ADuser cmdlet. In the second part of this series, we'll show you some more examples of Get-AD* cmdlets. We will also try to learn a bit of PowerShell scripting.

How To Use Common Active Directory cmdlets - Continue:

To continue with demo, I am going to show you some examples with Get-ADGroup and Get-ADGroupMember cmdlets.

Following command will return the information about Administrators group.
Get-ADGroup Administrators

Open in new window

Get-ADGroup ExampleFollowing command will return all group objects in your AD
Get-ADGroup -Filter *

Open in new window

Tip : You might have already spotted it, the syntax is similar to Get-ADUser. You will find the basic Parameters like -Identity, -Filter, -SearchBase, -SearchScope, -Properties etc. are similar in their usage for many Get-AD* cmdlets. Get-AD* cmdlets are typically harmless and easy to learn, so you can play around with it without causing any trouble in your environment. However I would recommend to do all your learning in a lab computer, until you are sure about what you are doing.. :-)
Similar to Get-ADUser, you can use the –SearchBase and -Properties parameter with
Get-ADGroup. For example, following command will list all groups from  OU 'Groups' and output will include MemberOf and Members properties of the objects.
Get-ADGroup -Filter * -Properties MemberOf,Members -SearchBase "OU=Groups,OU=HQ,DC=Max,DC=com"

Open in new window

Tip : One of the key concepts in Powershell is that everything is an object. An “Object” can be defined as something that we can collect information from and/or to perform some action upon it. PowerShell objects have Properties which we use to collect information and Methods which we use to perform the actions upon it.

For example, Get-Service cmdlet is used to list the services information. When you run this cmdlet, each service listed in the output can be considered as an object. In output we have default properties like Name, Status, DisplayName etc. and its values. The output object also contain methods which can be used to Start, Stop, or to make any other changes to the service.

You may refer the following articles to know more details about powershell objects.

Explaining Objects To Non-Programmers

Learning About Objects
?.. QUESTION : How can I get all security groups in my AD environment?

You guessed it right.. :-).. we can use –filter parameter or Where-Object cmdlet.
Get-ADGroup -filter {GroupCategory -eq "Security"}
                      Get-ADGroup –filter * | Where-Object {$_.GroupCategory -eq "Security"}

Open in new window

?.. QUESTION : How to export the result to a csv file?

Yes, you are right again.. We can use Export-CSV to export the result to a csv file..
Get-ADGroup -filter {GroupCategory -eq "Security"} | Export-CSV C:\report.csv

Open in new window

#... Now we will look in to some examples of cmdlet Get-ADGroupMember.

Get-ADGroupMember cmdlet is used to get the members of a particular group. Following cmdlet will list all members of  'Administrators' group.
Get-ADGroupMember Administrators

Open in new window

You can use -Recursive Parameter to find the recursive group membership.
Get-ADGroupMember Administrators –Recursive

Open in new window

#... Okie, enough with cmdlet examples.. Now we will learn a bit of PowerShell scripting!!

We will start with a simple example. I have seen many questions in PowerShell zone about exporting the group memberships. Here we have cmdlets to get all groups and the group’s members individually, so how do we combine this and get membership for a set of groups or all groups in AD? It’s very simple!

You just need to pipe the Get-ADGroup cmdlet result to Get-ADGroupMember input.

Oh Wait!  What is “piping” and “the pipeline.”?

Tip : Piping is another important feature/concept in PowerShell and we have already used it in many of our previous examples. Basically PowerShell allow the output of one command to be passed as the input to another. The official definition is following..

Pipelines act like a series of connected segments of pipe. Items moving along the pipeline pass through each segment. To create a pipeline in Windows PowerShell, you connect commands together with the pipe operator "|". The output of each command is used as input to the next command.

You may refer the following articles to know more details about powershell pipeline.

Piping and the Pipeline in Windows PowerShell :

Understanding the Windows PowerShell Pipeline :

Back to scripting!..

Following is the example of piping the Get-ADGroup cmdlet output to Get-ADGroupMember input.
Get-ADGroup –filter * | Get-ADGroupMember

Open in new window

Following code will list members of all Security groups in AD.
Get-ADGroup -filter {GroupCategory -eq "Security"} | Get-ADGroupMember

Open in new window

Group membership reportBut you might have noticed that something is wrong with this output. It is showing all members but how do we identify which group they belong to?  We are going to use ForEach-Object and some PowerShell tricks to achieve this.

Tip : The ForEach-Object cmdlet provides a way to loop through a collection of objects and perform an action on each item. Refer the following article to learn more about ForEach-Object.

Using the Foreach-Object Cmdlet  :

We will also create a custom object property to list the group name in final report. There are many ways to create custom object property in PowerShell.

Tip : You can refer the following articles for details about Custom Object.

Working With Custom Objects

Windows PowerShell: The Many Ways to a Custom Object :

We are going to use the following PowerShell code to export the group memberships.
Get-ADGroup -filter * | ForEach-Object {
                      $Group = $_.Name
                      Get-ADGroupMember $Group | 
                      	Select-Object @{Name="Group Name";Expression={$Group}},*
                      } | Export-Csv C:\Report.csv

Open in new window

I will split the code in to multiple parts and explain how it works..
Get-ADGroup -filter * | ForEach-Object {<Code to process>}
You already know that Get-ADGroup -filter * will list all group objects in AD. Above code will pass the output of Get-ADGroup cmdlet to ForEach-Object, then it will loop through each object in pipeline (in our scenario objects in pipeline are groups) and perform the action specified inside the code block (curly brackets)
$Group = $_.Name
The $_ is a variable created automatically by PowerShell to store the current pipeline object. This variable contains all properties of the pipeline object. You can also access specific property value from this variable, For example to access the value of property 'Name' we can use variable $_.Name and to access the value of property 'Xyz' we can use variable $_.Xyz.

In this line of code, we are assigning value of variable $_.Name to another variable called $Group (in our scenario the value is name of the Group).

Tip : What is Variable? Variable is nothing but a virtual container where we store information. We can use variables to store information that will be later utilized within a script.

You may refer following article for more details
In our code $Group is used as a variable which we will be using later in script to create a custom property.
Get-ADGroupMember $Group |
Remember the value stored in $Group variable is the name of the group. So with the above line, we can retrieve the members of that particular group and then pass it to the input of Select-Object cmdlet.
Select-Object @{Name="Group Name";Expression={$Group}},*
In the above line we are selecting all properties of the object from pipeline using the Select-Object cmdlet and also creating a custom property to display the group name in output. By adding ,* PowerShell will select all existing properties of the object along with the custom property.

Following is the format for creating custom property.
@{Name=< Property Name>;Expression={<Value of the Property>}}

Open in new window

In our scenario property name is "Group Name" and property value is the value stored in variable $Group.
} | Export-Csv C:\Report.csv
The output of the Select-Object cmdlet is then passed to the input of Export-Csv cmdlet to save the result in a CSV file. If you check the output csv file, it will have a new column with header Group Name.
New Group membership reportHope it’s clear..:-)

?.. QUESTION : Next question is, how do I get members of specific groups?

To accomplish this you can provide the group names in  text file or csv file.

For example if you have a text file with group name "Administrator" and "GroupA"..
Sample Input Text FileThen, you can use this code to get the report.
Get-Content C:\input.txt | ForEach-Object {
                      $Group = $_
                      Get-ADGroupMember $Group | 
                      	Select-Object @{Name="Group Name";Expression={$Group}},*
                      } | Export-Csv C:\Report.csv

Open in new window

We have only two changes in this code compared to previous one.

#.. First, We replaced Get-ADGroup -filter * with Get-Content C:\input.txt.

Get-Content cmdlet will read input text file C:\input.txt and pass it to the ForEach-Object cmdlet.

#.. Second, replaced $_.Name with $_

Is this case the values in pipeline is just a string, which doesn’t have any property. So we just assign the value in pipeline to the variable $Group. The value will be the group names which we have entered in the input text file.

If you have a csv file with group name entries ''Administrator'' and ''GroupA" and the header in the csv file is "Name".
Sample for Input csv file..Then, you can use following code to get the report.
Import-csv C:\input.csv | ForEach-Object {
                      $Group = $_.Name
                      Get-ADGroupMember $Group | 
                      	Select-Object @{Name="Group Name";Expression={$Group}},*
                      } | Export-Csv C:\Report.csv

Open in new window

The only change we have done is to replace Get-ADGroup -filter * with the command Import-csv C:\input.csv. Import-csv cmdlet is used to read the csv file. Rest of the code is same as our initial script.

That's all for now. See you in next article...

Note :
I appreciate the time you took to read my article, please leave your valuable feedback. Thanks in advance!..
SubSunIT Infrastructure Architect
Exchange Server and Active Directory Expert | PowerShell Enthusiast

Comments (1)

Very informative and easy to read .. Thanks Subsun !

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.