3

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

4

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]}}
2
  • 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. – Fylix Apr 10 '20 at 5:31
  • As a bonus, this will also work for AD containers which aren't proper OUs (such as "Computers" or "Users"). – Massimo Apr 10 '20 at 9:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.