Retrieve Active Directory User List from OU with Group Memberships

In this article, we’ll explore a PowerShell script to retrieve a list of users from a specified Organizational Unit (OU) in Active Directory (AD). This script also includes information about the groups to which each user belongs.

Prerequisites

  • Ensure that you have the Active Directory PowerShell module installed.
  • You must have the necessary permissions to access the AD.

PowerShell Script

# Define the OU where the users reside
$OUpath = 'OU=Disabled user,DC=example,DC=com'

# Define the path for the CSV file
$ExportPath = "C:\UsersWithGroups.csv"

# Import the Active Directory module-IF Required
Import-Module ActiveDirectory

# Get all users in the specified OU, including the MemberOf property
$users = Get-ADUser -Filter * -SearchBase $OUpath -Properties DistinguishedName, Name, UserPrincipalName, MemberOf

# Select relevant properties and export to CSV
$users | Select-Object DistinguishedName, Name, UserPrincipalName, @{Name='MemberOf';Expression={[string]::join('; ', ($_.MemberOf | ForEach-Object { (Get-ADGroup $_).Name }))}} | Export-Csv -Path $ExportPath -NoTypeInformation

Write-Output "User list with group memberships has been exported to $ExportPath"

Explanation of the Script

  1. Defining the OU:
    • The $OUpath variable specifies the path to the OU from which users will be retrieved. You can replace example with your actual domain name.
  2. Export Path:
    • The $ExportPath variable defines where the CSV file will be saved. Adjust this path if necessary.
  3. Importing the Module:
    • The Import-Module ActiveDirectory command loads the AD module, allowing access to AD cmdlets.
  4. Retrieving Users:
    • The Get-ADUser cmdlet fetches all users from the specified OU, along with their DistinguishedName, Name, UserPrincipalName, and MemberOf properties.
  5. Exporting to CSV:
    • The script then processes the user data, joining group names into a single string for each user and exporting the results to a CSV file.

Conclusion

This script simplifies the process of obtaining user information from Active Directory and is useful for administrators who need to manage user accounts and their group memberships effectively. Feel free to customize the script to meet your organization’s specific needs.

For any questions or comments, feel free to reach out!

Leave a Comment