Extract OU name using Powershell's Get-ADOrganizationUnit & Get-ADComputer

6,735

String manipulation is your friend.

Assuming:

$dn = "CN=ComputerName,OU=OU1,OU=OU2,OU=OU3,DC=domain,DC=org"

Then:

$OU = $dn.Split(',')[1].Split('=')[1]

What this does:

  • Split the "dn" string at each ','
  • Take the second element ("OU=OU1")
  • Split this at each '='
  • Take the second element
  • Assign the result to the variable '$OU'

At the end, the variable $OU contains the name of the first OU in the path where the object is contained ("OU1").

And yes, you can also use this when formatting your output:

Get-ADComputer -filter * -Properties ipv4Address, OperatingSystem,DistinguishedName | select-object Name, ipv4Address, OperatingSystem, @{label='OU';expression={$_.DistinguishedName.Split(',')[1].Split('=')[1]}}
Share:
6,735

Related videos on Youtube

Fylix
Author by

Fylix

Updated on September 18, 2022

Comments

  • Fylix
    Fylix over 1 year

    I want to get a list of servers on our Active Directory, I also want to include their IP, OS and what Organization Unit they belong to. It is the direct parent OU from which my servers belong to

    I came up with the following PS script and it almost satisfies what I need:

    
    > Get-ADComputer -filter * -Properties ipv4Address, OperatingSystem,DistinguishedName | select-object Name, ipv4Address, OperatingSystem, DistinguishedName
    
    

    However, the OU name is really the DistinguishedName and it is hard to see, what I really want is the 2nd OU value on that distinguishedname. I want to only show the value in those yellow box instead of the full name.

    enter image description here

    I tried to use Get-ADOrganizationUnit but it always give me blank. Here is my latest attempt, can you spot if I have something wrong in my PS script?

    > Get-ADComputer -filter * -Properties ipv4Address, OperatingSystem,DistinguishedName | select-object Name, ipv4Address, OperatingSystem, @{label='DistinguishedName';expression={(Get-ADOrganizationUnit $_.DistinguishedName -Property DistinguishedName).Name}}
    
    
  • Fylix
    Fylix about 4 years
    Thank you Massimo for your detail explanation, I thought about this approach too but the developer side in me immediately tried not to use string manipulation, instead I tried to utilize the existing Get-ADOrganizationUnit. I'll use your approach since it does what I need.
  • Massimo
    Massimo about 4 years
    As a bonus, this will also work for AD containers which aren't proper OUs (such as "Computers" or "Users").