Extract OU name using Powershell's Get-ADOrganizationUnit & Get-ADComputer
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]}}
Related videos on Youtube
Fylix
Updated on September 18, 2022Comments
-
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.
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 about 4 yearsThank 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 about 4 yearsAs a bonus, this will also work for AD containers which aren't proper OUs (such as "Computers" or "Users").