I'm trying to export lists of AD group members with powershell. I was doing great with commands like this:

Get-ADGroupMember "MyGroupName" -Recursive | Get-ADUser -Properties Company,Surname,GivenName,EmailAddress | select Company,Surname,GivenName,EmailAddress | Sort-Object -Property Company,Surname | Export-CSV $home\Desktop\MyGroupName.csv

Then I realized that I was only getting users and not getting contacts, and I need both. I spent a pile of time Googling for how to include contacts as well as users, delving into Get-ADObject and filtering with ObjectClass "contact", but I can't seem to find a simple way to dump a list of group members that includes both users and contact and displays the info I want.

One suggestion online was to use

(Get-ADGroup "MyGroupName" -Properties members).members

That gives me the DistinguishedNames of the members, including both users and contacts, but I can't figure out how to get the properties I want. The property names between contacts and users don't really align - mail vs. EmailAddress, etc. Also, piping that output to Get-ADUser, unsurprisingly throws errors on the contacts.

If I pipe it to something like this:

Get-ADObject -Filter 'objectClass -eq "contact"' -Properties CN,mail,company | Format-Table CN,mail,company

I get the info I want on the contacts, but it throws errors on all of the users. Any advice/assistance would be appreciated. Thanks!

1

There are 1 best solutions below

0
Jeff Zeitlin On

You'll need to process Users separately from Contacts, more or less. This isn't tested or complete, but should point the way for you:

(Get-ADGroup "MyGroup" -Properties Members).Members | Get-ADObject | ForEach-Object {
   if ($_.ObjectClass -eq "contact") {
       #emit what you want for a contact
   } elseif ($_.ObjectClass -eq "user") {
       #emit what you want for a user
   } else { #it's probably a group, but ...
       #process whatever isn't a user or a contact
   }
}

What this does when you fill in the comments with your real code is

  1. Gets the members from the group
  2. Passes them to Get-ADObject, to get things like email, name, et cetera
  3. Passes that result to ForEach-Object which then
    1. Inspects the object to see what type it is (user, contact, something else), and
    2. process the object based on the type, since the fields for each object type are apparently different.