Split string(s) into substrings.
Syntax
.Split(strSeparator [, MaxSubstrings] [, Options])
String -Split strSeparator [, MaxSubstrings] [, Options]
String -Split {scriptblock} [, MaxSubstrings]
-Split String
Key
strSeparator The character used to split up each string, by default whitespace (space/newline/tab).
MaxSubstrings The maximum number of substrings, by default all.
Options
"SimpleMatch [,IgnoreCase]"
"[RegexMatch][,IgnoreCase] [,CultureInvariant]
[,IgnorePatternWhiteSpace] [,ExplicitCapture]
[,SingleLine | MultiLine]"
RegexMatch is the default. SimpleMatch uses simple string comparison when evaluating strSeparator
IgnoreCase will force Case insensitive matching even if -cSplit is specified.
CultureInvariant will ignore cultural differences when evaluating strSeparator.
IgnorePatternWhiteSpace will ignore unescaped whitespace and comments.
MultiLine recognises the start and end of Lines and Strings.
SingleLine recognises the start and end of Strings.
When the strings are split the strSeparator is omitted from all the substrings.
Examples
Split a string by the - character:
PS C:\> "abc-def" -split "-"
abc
def
Split a string by the \ character, note this has to be doubled:
PS C:\> "abc\def" -split "\\"
abc
def
Split a string by a space:
PS C:\> $demo = "abc def"
PS C:\> $demo.split()
abc
def
Split up the pathext environment variable:
PS C:\> $env:pathext -split ';'
PS C:\> $env:pathext -split ';' -replace '\.','*.'
When using Split() against a text file or the string output of a command, you are dealing with an array. PowerShell automatically converts each line of the text file to an element of the array. This makes the file easy to work with, but does means the syntax for split() is slightly different.
Wrong:
PS C:\> $demo = get-content C:\demo\sales.txt
PS C:\> $demo.split()
Method invocation failed because [System.Object[]] doesn't contain a method named 'split'.
At line:1 char:10
+ $demo.split <<<< ()
+ CategoryInfo : InvalidOperation: (split:String) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound
Right:
PS C:\> $demo = get-content C:\demo\sales.txt
PS C:\> $demo[2].split()
Or to split all the lines:
PS C:\> $demo = get-content C:\demo\sales.txt
PS C:\> $demo | %{$_.split()}
“Let the gentle bush dig its root deep and spread upward to split the boulder” ~ Carl Sandburg
Related:
PowerShell Methods
help about_split
© Copyright SS64.com 1999-2013
Some rights reserved