Export list of users from multiple OUs

Lt. Columbo 281 Reputation points

Hi guys,

I've come across this script to export Ad users from multiple OUs.

'OU=1,DC=domain,DC=com','OU=2,DC=domain,DC=com' | ForEach-Object {

    Get-ADUser -Filter * -SearchBase $_ -Properties DisplayName,EmailAddress

} | Select Name,GivenName,Surname,DisplayName,SamAccountName,EmailAddress |
        Export-Csv .\userList.csv -NoTypeInformation

However, because I have around 100 OUs ideally I need insert OUs in some other way (may be from txt file with Get-Content)
Also, the outcome of this script doesn't include the information which OU a user is located in.

Is it possible modify this script they way I need?

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
4,904 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ian Xue (Shanghai Wicresoft Co., Ltd.) 19,141 Reputation points Microsoft Vendor


    You can add the DistinguishedName attribute of the AD user to the output.

    $ous = 'C:\temp\ous.txt'  
    $userlist = 'C:\temp\userlist.csv'  
    Get-Content -Path $ous | ForEach-Object {      
         Get-ADUser -Filter * -SearchBase $_ -Properties DisplayName,EmailAddress     
    } | Select Name,GivenName,Surname,DisplayName,SamAccountName,EmailAddress,DistinguishedName |  
             Export-Csv -Path $userlist -NoTypeInformation  

    Best Regards,
    Ian Xue


    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 39,266 Reputation points

    The Get-OrganizationalUnit cmdlet will return a list of all your OUs. You can remove the ones you don't want.

    OTOH, if you want ALL the users regardless of the OU, just remove the -SearchBase from the Get-ADUser cmdlet.

    0 comments No comments