Showing User OU from Active Directory with Powershell

The need :

You need to export your Active Directory users and need to get an “OU” parameter for each user to be able to migrate user, create reports or whatsoever. For this you need a powershell result with the samaccountname and OU of the user. This simple script will allow you to parse this information in one powershell object you can reuse in you scripts.


The code :

$Result = @()   #Custom PS Object

ForEach ($ou in (Get-ADOrganizationalUnit -Filter *)) {
    $users = Get-ADUser -Filter * -SearchBase $ou.distinguishedname -SearchScope OneLevel #Getting all users from an OU
	ForEach ($user in $users){
		$prop = @{
        	    OU = $ou.distinguishedname
        	    User = $user.samaccountname
		$NewObject = New-Object -TypeName psobject -Property $prop
		$Result += $NewObject


The result

Information Technology addict since Windows 3.11, I specialised myself on Cloud technologies. I did not forget my development skills in Scripting (Powershell) and Web (PHP,CSS,HTML,Javascript). I love sharing my knowledge and help companies in their cloud journey. Feel free to contact me.