Shawn Robinson
Shawn Robinson

Reputation: 13

How to grab a portion of an LDAP string into a variable (Powershell)

I am able to get the full LDAP path into a variable $strPath and it will return a result such as:

LDAP://CN=computername,OU=City,OU=Servers,OU=###,DC=dom,DC=ain,DC=com or in other locations it could look like: LDAP://CN=computername,OU=Servers,OU=##,DC=dom,DC=ain,DC=com

I want to return only the ##, ### or #### value (it can be either two, three or four characters) which is our district code.

So some computer objects have a city name in their LDAP string while others do not (depending on the size of the district), and the district code can be two, three or four characters long.

I'm guessing I want to do something like find text "Servers,OU=" and remove everything including and before that and also remove text ",DC=dom,DC=ain,DC=com" to get my final variable.

Thanks in advance!

Upvotes: 1

Views: 1866

Answers (2)

Bill_Stewart
Bill_Stewart

Reputation: 24575

You may be interested in the ADName module I wrote:

https://github.com/Bill-Stewart/PowerShell-ADName

For your first example, the OU code is the 4th element from the right:

LDAP://CN=computername,OU=City,OU=Servers,OU=###,DC=dom,DC=ain,DC=com

So for example, you can write this:

(Get-ADName "LDAP://CN=computername,OU=City,OU=Servers,OU=###,DC=dom,DC=ain,DC=com" -Split -ValuesOnly)[-4]

The -Split parameter splits the LDAP path into an array, and -ValuesOnly omits the CN=, OU=, DC=, etc. The [-4] means "return the 4th element from the end of the array."

Upvotes: 2

Norman Skinner
Norman Skinner

Reputation: 6985

How about something like this:

$ldapString = "LDAP://CN=computername,OU=Servers,OU=##,DC=dom,DC=ain,DC=com"
$temp = $ldapString.Split(",=")
$districtCode = $temp[[array]::IndexOf($temp,"DC") - 1]

It works with both and no extra imports. As long as you do not have a district code that is "DC".

Upvotes: 0

Related Questions