How to determine the Organization Unit a computer is in using PowerShell

Home > Search > How-to
  by

Create a variable that will get the computer name.

$ComputerName = $env:computername
echo $ComputerName

 

In this example, the computer name is US-H2LXQ72.

 

The next set of variables will list the Canonical Name (CN), Organizational Units (OU), and Domain Controller (DC) the computer is in.

$ComputerName = $env:computername
$Filter = "(&(objectCategory=Computer)(Name=$ComputerName))"
$DirectorySearcher = New-Object System.DirectoryServices.DirectorySearcher
$DirectorySearcher.Filter = $Filter
$SearcherPath = $DirectorySearcher.FindOne()

echo $SearcherPath

 

In this example, the Canonical Name of the computer is US-H2LXQ72, the computer is in the USA > Windows_7 Organizational Unit, and the computer is a member of the Software.Eng.APL domain.

 

The Distinguished Name variable can be used to remove Path and LDAP from the output.

$ComputerName = $env:computername
$Filter = "(&(objectCategory=Computer)(Name=$ComputerName))"
$DirectorySearcher = New-Object System.DirectoryServices.DirectorySearcher
$DirectorySearcher.Filter = $Filter
$SearcherPath = $DirectorySearcher.FindOne()
$DistinguishedName = $SearcherPath.GetDirectoryEntry().DistinguishedName

echo $DistinguishedName

In this example, the computer named MyHostname is in the Windows10 OU, and the Windows10 OU is a child of the USA OU.

 

The following can be added to only display the lowest OU the computer is in.

$OUName = ("$DistinguishedName".Split(","))[1]
$OUMainName = $OUName.SubString($OUName.IndexOf("=")+1)

echo "The computer named $($ComputerName) is in the $($OUMainName) OU"

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments