powershellpowershell-v6.0

How can I get the number of bytes in a newline from PowerShell?


DOS/Windows newline is two (2) bytes, 0x0D0A. UNIX/Linux newline is one (1) byte, 0x0A. Mac newline is one (1) byte, 0x0D.

How can I write code to find the length of a newline on each platform? Output on Windows will produce two (2) bytes, but output on Linux will produce one (1) byte. I did not find anything related to this in about_Special_Characters.

On Windows:

PS C:\src\t> type .\nl.ps1
'`n'
'`n'.Length
"`n"
"`n".Length

Both Windows and Linux return the same result.

PS C:\src\t> .\nl.ps1
`n
2


1

Solution

  • .NET Standard has an API for that, and is a always available from Powershell:

    [system.environment]::newline.length
    

    On Windows

    PS> [system.environment]::newline.length
    2
    

    On Ubuntu

    PS> [system.environment]::newline.length      
    1