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

Advertisements
This entry was posted in Powershell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s