powershellsplitpowershell-5.1powershell-7

Split behaviour changes when script is run with PS2EXE


If I run this code as a ps1-file in the console it gives the expected output, but if I 'compile' the script with PS2EXE there's no second part of the string:

$a = "first Part`r`n`r`nsecond Part"
$a
$b = $a.split("`r`n`r`n")
$c = $b[0]
$d = $b[1]
write-host "Part 1: $c"
write-host "Part 2: $d"

Console: screenshot of ps1 output

Exe: screenshot of exe-output

Somehow the executable seems to be unable to split the string correctly. Any ideas?


Solution

  • I've come to an explanation, finally: I wrote the above code with Powershell 7, whereas ps2exe uses Powershell version 5. These two versions differ in handling a split command, as I try to show with the following code. If you run it under PS 5, the parts of the split string will be stored in $b[0] and $b[1] only if you use a one-character-delimiter. With each added character to the delimiter the second value will be stored at one index higher. But if you run the code under PS 7, the values will always be stored in [0] and [1].

    $delimiter = "@@"
    $a = "first Part$($delimiter)second Part"
    write-host "String to split: $a"
    write-host "Delimiter: $delimiter`r`n"
    $b = $a.split($delimiter)
    write-host "`t0: $($b[0])"
    write-host "`t1: $($b[1])"
    write-host "`t2: $($b[2])"
    write-host "`t3: $($b[3])"
    write-host "`t4: $($b[4])"
    

    Just in case someone runs into the same issue.

    Thanks for the advice, Booga Roo.