Friday, August 16, 2013

How to Get a User OU using PowerShell

To know the user OU you can use the Get-ADUser Command
Check this:
Get-ADUser -Id User1 | FL








Depending the the DistinguishedName Value we can get the user OU.
Notice that the value is CN=User DisplayName,OU=...
So we need to remove the CN=DisplayName, and the remaining path will be for the OU.


Import-Module activedirectory #Import Active Directory Module
$user=Get-ADUser user1 | select DistinguishedName,name # will read AD and get the DN for the user
$OU=$user.DistinguishedName.Trim("CN=" + $user.name+",")  #using the Trim Command to remove the CN= and user Displayname and the comma "," and assign the value to a variable named as OU
$OU # write the output

No comments: