Powershell command to list all users in an OU and user's group membership

brichardi 361 Reputation points
2022-09-02T19:57:27.237+00:00

Hello Scripting Guru,

I just can't seems to find a way to have powershell to list all users in an OU and the group membership of all each users.

This is my PS command:

Get-ADUser -Filter * -SearchBase 'OU=Admin,OU=Users,DC=contoso,DC=com' -Properties MemberOf |Select-Object SamAccountName, @{n='memberOf';e={$_.memberOf -replace '^CN=([^,]+).+$','$1' }}

And this is the output:

jsmith contoso-Employees O365 A5 Employees Remote FINANCE Accounting All Employees DL-Financial Secretaries DL-Administration - OSP HERT-GLOBAL DL-AdvantageGroup OSP-OFFICE Audit.

How do I change the PS command so it will list user account with membership like below:

SamAccountName Member of
Jsmith contoso-Employees
O365 A5 Employees
FINANCE Accounting
All Employees

Jdoe All Employees
Security Admin
Citrix Admin
Citrix VDI

Thanks for your help

Windows for business | Windows Client for IT Pros | Directory services | Active Directory
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 60,161 Reputation points
    2022-09-02T21:39:50.047+00:00

    So you just want to pretty print the output a little. Something like this would work I believe.

       Get-ADUser -Filter * -SearchBase 'OU=Admin,OU=Users,DC=contoso,DC=com' -Properties MemberOf |Select-Object SamAccountName, @{n='memberOf';e={$_.memberOf -replace '^CN=([^,]+).+$','$1' }}  | foreach-object { Write-Host $_.SamAccountName; Format-List -InputObject $_.memberOf; Write-Host ""; }  
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.