Sunday, November 4, 2012

Using a Calculated Property to Display Group Membership

A forum recently had a question about obtaining a list of contacts and their group membership in a CSV file. At first I figured the person was just lazy and hadn't done a bit of basic research. However, it turned out to be a bit more complicated that I expected.

I ran into two issues:
  1. Get-Contact does not return group memberships for contacts. The good news is you can work around this by using Get-ADObject -Filter {ObjectClass -eq "contact"} -Properties MemberOf.
  2. The MemberOf attribute is returned as an array which does not export properly to a CSV file. For this you need to create a new calculated property that is a string.
The final result was this:
Get-ADObject -Filter {ObjectClass -eq "contact"} -Properties MemberOf | Select-Object Name,@{Name='Groups';Expression={$_.MemberOf -join ";"}} | Export-CSV C:\contacts.csv

Let's break this down a bit:
  • The -Properties parameter is used to specify an AD attribute that you want to retrieve for an object. By default, the Get-ADObject retrieves only a default set of attributes. You need to use -Properties to get more than that. You can use -Properties * to get all attributes.
  • The Select-Object cmdlet limits the properties collected for each contact. Prunes them down to the Name property and a new calculated property Groups.
  • The creation of calculated property Groups is within the @{}. This Name='Groups' defines the name. The Expression={} defines the value of the property. In this instance, it takes each instance of the MemberOf array and joins it together into a single value separated by a semicolon. Each contact will have a single Groups attribute with a single value which is a long concatenated list of the groups that contact is a member of.
  • Export-CSV dumps the list of contacts and their group memberships to a CSV file that is easy to sort in Excel.
The original question in the forum was actually about obtaining a list of contacts that were not members of a group. That was actually easier:
Get-Contact -Filter {MemberOfGroup -eq $null}

No comments:

Post a Comment