0

I need the marked part bellow of the distinguished name of an computer:

CN=X, OU=EXAMPLEOU, OU=D, DC=A, DC=B, DC=C

I just need OU=EXAMPLEOU.

How I get this part of the distinguished name:

$OU = Get-ADComputer -Identity $env:computername -Properties * | select @{N="OU";E={$_.DistinguishedName.Split(',')[-5].split('=')[1]}}

The output is:

OU
___
EXAMPLEOU

BUT I want the endresult to be a string that just returns EXAMPLEOU.

How can I do that? THANK YOU!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user18209625
  • 139
  • 2
  • 15
  • 1
    I'm guessting `OU=X` is actually `CN=X` isn't it? – Santiago Squarzon Mar 31 '22 at 01:35
  • 1
    I would recommend you to use the regex from this answer https://stackoverflow.com/questions/21782505/powershell-split-string-with-escaped-separator-characters to answer your question, you just need to use dot notation, `$ou.ou` – Santiago Squarzon Mar 31 '22 at 01:51

1 Answers1

0

You don't need to use Select. Just wrap the Get-ADComputer command in parentheses and use it like an object.

I would also suggest not using -Properties * since that will get all of the attributes when you only need one. So just tell it which one you need and you'll save time and bandwidth.

So it would look like this:

$OU = (Get-ADComputer -Identity $env:computername -Properties DistinguishedName).DistinguishedName.Split(',')[-5].split('=')[1]
Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84