Search code examples
powershellscriptingmembership

How to display AD group name next to AD user with PowerShell


I am a new PowerShell user and am trying to figure out how to get a list of users from a group with the group name displayed.

Desired output:

Username      AD Group       Department
john          SG-MSOffice    IT
jane          SG-MSOffice    Accounting
sam           SG-MSOffice    Accounting
thomas        SG-MSOffice    IT

Current output:

Code:

 Get-ADGroupMember -identity SG-MSOffice | Get-ADObject -Properties   name,department,manager

Output:

Department
DistinguishedName
manager
Name
ObjectClass
ObjectGUID

Solution

  • Store the group name somewhere and use Select-Object to format the output you want, like:

    $groupname = "SG-MSOffice"
    Get-ADGroupMember -Identity $groupname | Select-Object -Property @{n="Username";e={$_.Name}}, @{n="AD Group";e={$groupname}}, Department
    

    I can't remember if Department is available in the "default"-object, if not, you could include something like Get-ADObject:

    $groupname = "SG-MSOffice"
    Get-ADGroupMember -Identity $groupname |
    Get-ADObject -Properties Name, Department |
    Select-Object -Property @{n="Username";e={$_.Name}}, @{n="AD Group";e={$groupname}}, Department