Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell -split on Pipe Character

Consider the ASCII text file test1.txt:

a,b,c
d,e,f

And the following Powershell Script test1.ps1:

$input -split "`n" | ForEach-Object {
    $row = $_ -split ","
    $row[0]
}

The output is, as excpected:

a
d

However, if we change the separator to | everything fails as in test2.txt:

a|b|c
d|e|f

And the following Powershell Script test2.ps1:

$input -split "`n" | ForEach-Object {
    $row = $_ -split "|"
    $row[0]
}

The output is all but empty. Why does the -split fail?

like image 793
Marc Avatar asked Nov 08 '16 14:11

Marc


1 Answers

It seems -split expects a regular expression and thus you need to escape the pipe as in:

$row = $_ -split "\|"

Or specify the SimpleMatch option to split on the literal string or character:

$row = $_ -split "|", 0, "SimpleMatch"

The 0 stands for MaxSubstrings: "The maximum number of substrings, by default all (0)."

Source: http://ss64.com/ps/split.html
Also: Get-Help about_Split

like image 99
Marc Avatar answered Sep 28 '22 10:09

Marc