Add Multi-Line Content to a Linux File with Add-Content

You have a large number of files to edit that are used by Linux servers. The editing and distributing of these files has to be done on a Windows platform. You want to append some multi-line detail to these files with PowerShell, but the file still needs to be compatible with Linux.

Now, Add-Content with a here string would seem to be a good way to go.

 

 
$a = @"
#TITLE OF LINE
here is the Unix stuff
"@

Add-Content -Value $a -Path .\linux

 

Unfortunately, because of the way Windows handles a new line, when this file is processed by Linux you'll see ^M at the end of each line in the file. What's going on? Well, the ^M represents 0x0D or carriage return, which you may also know as \r or `r. When you press Enter in Windows you get a new line `n (or \n or 0x0A or ^J) AND a carriage return, i.e. \n\r. This mimics the behaviour of a type writer. In the Unix world you only get the newline character.

How to add a Linux friendly entry with Add-Content?

 

 
$a = "`n#TITLE OF LINE`n\here\is the\unix\stuff`n"

Add-Content -Value $a -Path .\linux

In Notepad it will appear as a single line, however, in Linux you'll have the desired multi-line output.