Herestring and splitting by lines

Hello,

I’m sure this is quite a simple problem, but I’ve searched around and haven’t found a similar question. Here’s my code:

function FormallyAsk([string] $question)
{
    $line = $question.Split([System.Environment]::NewLine)
    $line
}

$answer = FormallyAsk(@"
Are you sure you want to quit?

[ Yes ] [ No ]
"@)

Write-Output([string]::Join("<->", $answer))

When I run this, my output looks like this:

Are you sure you want to quit?<-><-><-><->[ Yes ] [ No ]

I don’t understand why I’m getting double the number of new line splits I would expect. I took a look at the binary for the script I’m working on and it has normal Windows line endings:

I’ve also confirmed that [System.Environment]::NewLine contains a 0D followed by a 0A:

Write-Output([byte][char] [System.Environment]::NewLine[0])
Write-Output([byte][char] [System.Environment]::NewLine[1])
Write-Output([byte][char] [System.Environment]::NewLine[2])

Reports:

13
10
0

Does anyone know why my output looks so unexpected? It’s possible I am misunderstanding how it should work, but I’m just going by my experience with split methods in other languages.

Benjamin,
Welcome to the forum. :wink:

If this isn’t just an example and your actual issue is something else I’d recommend using another method asking for user input. There is a dotNet method called PromptForChoice you could leverage to get a users choice.

It limits the chances for invalid inputs.

Here are some examples:

2 Likes

It looks like the Split() method for the String class returns different results in PowerShell 5.1 (.NET Framework) and PowerShell 7.x (.Net Core).

PowerShell’s -split operator gives consistent results on both versions of PowerShell.

$line = $question -split [System.Environment]::NewLine
1 Like

I ran your code and got only two “<->” separators. Just to verify that your assumptions are correct, place this line between line 11 “@) and line 13 Write-Output(\[string\]::Join("<->", $answer)):

Write-Host $answer.count

Do you get the expected answer (3)?