export_domain_users_with_upn_ou_and_group_membership

Export Domain Users with UPN, OU, and Group Membership

Objective

Generate a CSV file listing all Active Directory users in the domain, including:

  • User Principal Name (UPN)
  • Organizational Unit (OU) path
  • Groups the user is a member of (direct memberships only)

Scope

This procedure is intended for domain administrators with access to a Domain Controller or a management workstation with RSAT (Active Directory module for PowerShell) installed. It retrieves all users in the domain and exports the results to a CSV file for reporting or auditing purposes.

Requirements

  • PowerShell 5.1 or later
  • Active Directory PowerShell module (`ActiveDirectory`)
  • Sufficient permissions to query Active Directory

Procedure

  1. Log in to a Domain Controller (or a workstation with RSAT installed) using an account with AD read permissions.
  2. Open PowerShell as Administrator.
  3. Run the following script:
Import-Module ActiveDirectory
 
Get-ADUser -Filter * -Properties UserPrincipalName,MemberOf |
    Select-Object `
        @{Name='UserPrincipalName'; Expression = { $_.UserPrincipalName }},
        @{Name='OU'; Expression = {
            ($_.DistinguishedName -split '(?<=^CN=.*?),')[1] -replace '^,',''
        }},
        @{Name='Groups'; Expression = {
            if ($_.MemberOf) {
                # Convert DN of each group to just the CN name
                ($_.MemberOf | ForEach-Object {
                    ($_ -split ',')[0] -replace '^CN='
                }) -join ', '
            }
            else {
                ''
            }
        }} |
    Export-Csv -Path "C:\Temp\DomainUsers_OU_Groups.csv" -NoTypeInformation -Encoding UTF8
  1. The script will create a file named DomainUsers_OU_Groups.csv in `C:\Temp`.
  2. Open the CSV file in Excel or another spreadsheet tool to view the results.

Notes

  • The `Groups` column shows direct group memberships only. Nested group memberships are not expanded for performance reasons.
  • For a full list including nested groups, replace the `MemberOf` logic with a call to `Get-ADPrincipalGroupMembership`, but note this will slow down the process considerably for large domains.
  • You can limit the search to a specific OU by adding the `-SearchBase` parameter to `Get-ADUser`.

References

export_domain_users_with_upn_ou_and_group_membership.txt · Last modified: 2025/08/14 14:55 by oso