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
	}
}
$Result

 

The result