1

I'm trying to grab a value from a string within my PowerShell script.

The string can come like this:

$TargetOU = "OU=Company Users,OU=Company,OU=Organisation Users,DC=domain,DC=local"

or like this:

$TargetOU = "OU=Company,OU=Organisation Users,DC=domain,DC=local"

Using the following will return "Company" in the first example but "Company,OU" in the second. How Can I modify this to provide just "Company" in both instances?

$TargetOU.Split('= ')[1]

3 Answers 3

2

You can achieve this by adding a , to the characters in your split method. This is because you split your string at every char given to the split method. Your first string splits to:

OU
Company
Users,OU
Company,OU
Organisation
Users,DC
domain,DC
local

while your second string splits to:

OU
Company,OU
Organisation
Users,DC
domain,DC
local

When using $TargetOU.Split('= ,') instead your second string will split to:

OU
Company
OU
Organisation
Users
DC
domain
DC
local

where the element with index 1 is only "Company", not "Company,OU"

Sign up to request clarification or add additional context in comments.

1 Comment

Spot on thanks. I was reading it as start at "=" and finish at " " rather than splitting at all characters given. So simple and exactly what I was after. Thanks again.
2

Try this. Given your examples of input this returns "Company" every time.

What it does: saves your split in a variable and checks if that variable contains a comma, as it would if "OU=Company,OU=Organisation Users,DC=domain,DC=local" was your input. If true, split that again at the comma and save the first part in a variable. I used the same variable name as with the first split, since I assume you want to do the same thing with the result later in your script, regardless of how the input looks.

$SplitTargetOU = $TargetOU.Split('= ')[1]
if ($SplitTargetOU -like '*,*')
{
$SplitTargetOU = $SplitTargetOU.Split(',')[0]
}

EDIT: J. Bergmann's answer was a little simpler. Nice one. :)

Comments

0

This answer doesn't work for me. The split method is not treating the characters as a character array. To fix it, I have to explicitly cast it:

"OU=Company Users,OU=Company,OU=Organisation Users,
 DC=domain,DC=local".Split('= ,')

returns

OU=Company Users,OU=Company,OU=Organisation Users,DC=domain,DC=local

but

"OU=Company Users,OU=Company,OU=Organisation Users, 
 DC=domain,DC=local".Split([char[]]'= ,')

returns

OU
Company
Users
OU
Company
OU
Organisation
Users
DC
domain
DC
local

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.