Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

Use "`n" (not "`r`n") to split here document in PowerShell

Context:

  • You have to write "`r`n" to write CRLF to a file.
  • You can make here document (multi-line string literals) with @‘~’@.

Problem:

Some articles in web use "`r`n" to split here document in PowerShell like:

@'
abcde
fghij
'@.Split("`r`n") | Set-Variable foo

This works fine in interactive mode (command mode). But this doesn’t work if you put above code into .ps1 file and execute by dot source (. .\foobar.ps1) on Windows, or if you use Powershell on Linux. In those situation, the here document will not be split and whole string will be set to variable foo directly.

Reason:

This is because of using "`r`n" to split here document (PowerShell uses different internal CR/LF pair in interactive mode and batch mode?).

Solution:

Use "`n" instead of "`r`n" in argument of Split() and it will work fine in dot source and Linux environment.