Monthly Archive

Categories

PowerShell split

The PowerShell split operator is used to split strings based on a delimiter.

 

The default delimiter is white space

PS> $str = 'AA BB CC DD EE FF GG'

PS> -split $str
AA
BB
CC
DD
EE
FF
GG

 

You can define a delimiter

PS> $str = 'AA-B-CC-DD-EE-FF-GG'
PS> $str -split '-'
AA
B
CC
DD
EE
FF
GG

 

Notice that the position of the operator has changed. The first case using the default delimiter is a special case that’s equivalent to:

PS> $str = 'AA BB CC DD EE FF GG'
PS> $str -split ' '
AA
BB
CC
DD
EE
FF
GG

 

You can define the items into which the string is split:

PS> $str = 'AA BB CC DD EE FF GG'
PS> $str -split ' ', 3
AA
BB
CC DD EE FF GG

 

In this case you get the first two splits and the rest as one big string

The delimiter is normally removed from the results but you can keep it

PS> $str = 'AA-B-CC-DD-EE-FF-GG'
PS> $str -split '(-)'
AA
-
B
-
CC
-
DD
-
EE
-
FF
-
GG

 

You have a number of options you can use

"SimpleMatch [,IgnoreCase]"

or

"[RegexMatch] [,IgnoreCase] [,CultureInvariant]
[,IgnorePatternWhitespace] [,ExplicitCapture]
[,Singleline | ,Multiline]"

which are all documented in about_split

Comments are closed.