Why does the following result in an array with 7 elements with 5 blank? I\'d expect only 2 elements. Where are the 5 blank elements coming from?
$a = \'OU=RA
It splits the string for each character in the separator. So its splitting it on 'O', 'U' & '='.
As @mklement0 has commented, my earlier answer would not work in all cases. So here is an alternate way to get the expected items.
$a.Split(',') |% { $_.Split('=') |? { $_ -ne 'OU' } }
This code will split the string, first on ,
then each item will be split on =
and ignore the items that are OU
, eventually returning the expected values:
RAH
RAC
This will work even in case of:
$a = 'OU=FOO,OU=RAH,OU=RAC'
generating 3 items FOO
, RAH
& RAC
To get only 2 string as expected you could use following line:
$a.Split('OU=', [System.StringSplitOptions]::RemoveEmptyEntries)
Which will give output as:
RAH,
RAC
And if you use (note the comma in the separator)
$a.Split(',OU=', [System.StringSplitOptions]::RemoveEmptyEntries)
you will get
RAH
RAC
This is probably what you want. :)