Reputation: 487
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]
Upvotes: 1
Views: 508
Reputation: 89
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
Upvotes: 0
Reputation: 38
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. :)
Upvotes: 2
Reputation: 470
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"
Upvotes: 2