f

Split()

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 - match with regular expression.
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 a Mac address and convert each number:

$MacAddress ="12-34-56-78-9A-BC"
($MacAddress.split('-') | foreach {[byte] ('0x' + $_)} )
18
52
86
120
154
188

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 you do have to specify the line that you want to split.

PS C:\> $demo = get-content C:\demo\sales.txt
PS C:\> $demo[2].split()

Or split all the lines and match the tokens you want to retrieve:

$data = get-content C:\demo\sales.txt
$data | foreach {
   $items = $_.split("=")
   if ($items[0] -eq "ProductA"){Echo $items[1]}
}

If the string you're splitting is a Windows path, you may want to use the specialised Split-Path command.

“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-2014
Some rights reserved