In the previous post I showed how to generate the parent OUs by splitting and rejoining a string.
I used the operators –split and –join
These were introduced in PowerShell v2. In PowerShell v1 we had to use the split() method and stitch the thing back together ourselves using string concatenation.
lets start with a string
$string = "aaa#bbb#ccc#ddd#fff"
Not very imaginative but it works
We can split it up
PS (3) > $string -split "#"
aaa
bbb
ccc
ddd
fff
Notice we lose the character used for splitting. Just for fun we also have –isplit and –csplit available if we need them
The delimiter is the character( s ) we use as the dividing points. need to be aware if splitting on a “.”
Lets change all the “#” to “.”
$string2 = $string.Replace("#",".")
$string2 -split "." doesn’t quite give is what we want. We need to use
$string2 -split "\."
Regular expressions are used in the background and “.” means any character so we use a “\” too escape it to a literal character
Alternatively use
$string2 -split ".",0,"simplematch"
where 0 indicates the number of substrings returned – 0 implies all
Try these to see the differences
$string2 -split ".",1,"simplematch"
$string2 -split ".",2,"simplematch"
$string2 -split ".",3,"simplematch"
$string2 -split ".",4,"simplematch"
$string2 -split ".",5,"simplematch"
$string2 -split ".",6,"simplematch"
Other options available are
"SimpleMatch [,IgnoreCase]"
"[RegexMatch] [,IgnoreCase] [,CultureInvariant]
[,IgnorePatternWhitespace] [,ExplicitCapture]
[,Singleline | ,Multiline]"
see get-help about_split