Search code examples
powershellnewlineappveyorherestring

Where does PowerShell get the newline characters it puts in here strings?


Consider the following PowerShell code:

@"


"@.GetEnumerator() | %{[int]$_}

On my computer this outputs

13
10

which are the decimal representation of the ASCII control characters for carriage return and line feed, respectively.

The same code executed on AppVeyor outputs just a single number:

10

In other words, there seems to be variation between the characters PowerShell uses in here strings across systems. I expected the source to be [System.Environment]::newline but the same environment AppVeyor environment that output the single character in the here string, output

13
10

for [System.Environment]::newline. [System.Environment]::newline doesn't seem to be the source for newlines in here strings.


Solution

  • PowerShell script is essentially a string. And it already have to use "`n" or "`r`n" for line separation. So, if PowerShell string literal cross multiple lines, then PowerShell parser keeps line separators, which was used inside this string literal, as part of string literal value.

    For example this:

    "'a`nb`r`nc'.GetEnumerator() | %{[int]`$_}" | Set-Content .\Test.ps1
    .\Test.ps1
    

    will print:

    97
    10
    98
    13
    10
    99