Search notes:

PowerShell: -Split Operator

The -split operator splits a string into an array of strings.
There is a unary and a binary variant of the operator;
The unary variant splits on consecutive whitespaces:
PS C:\> -split "one two     three`tfour`t `tfive"
one
two
three
For the binary variant, the first operand is the string to be split, the second argument the pattern on which to split:
PS C:\> 'one two   three' -split ' '
one
two


three
It's possible to use regular expressions in the second operand
PS C:\> "one two   three`t `tfour" -split '\s+'
one
two
three
four
In order to retain the value that separates the splitted parts, a regexp-capturing group (the sub-pattern within the parantheses) needs to be used;
PS C:\> '12+345/6*78-9' -split '([+/\-*])'
12
+
345
/
6
*
78
-
9
The result of a split can be joined, for example to produce a nicer string:
PS C:\> '12+345/6*78-9' -split '([+/\-*])' -join ' '
12 + 345 / 6 * 78 - 9

Splitting a string into its characters

Using the empty character to split a string produces an array that consists of the characters of the string plus one empty string at either end of the array:
PS: > ('abc' -split '') -join '*'
*a*b*c*
A string can be split into an array of its characters without such empty characters using the string's ToCharArray() method:
PS:> 'abcde'.ToCharArray() -join '*'
a*b*c*d*e

Splitting a string into pairs of characters

A string can be split into pairs of characters like so:
'abcdef' -split '(..)' -ne ''
This is especially useful if the string contains a hexadecimal representation of a binary stream and a byte array should be produced from it.
[byte[]] $hex_values = 'DeadBeef11Cafe' -split '(..)' -ne '' | foreach-object { invoke-expression "0x$_" }

See also

.NET: splitting strings with String.Split()

Index