Adding a newline (line break) to a Powershell script Adding a newline (line break) to a Powershell script powershell powershell

Adding a newline (line break) to a Powershell script


  • $str_msg = $file,[System.IO.File]::ReadAllText($file.FullName) doesn't create a string, it creates a 2-element array ([object[]]), composed of the $file [System.IO.FileInfo] instance, and the string with the contents of that file.

  • Presumably, the .AddMsg() method expects a single string, so PowerShell stringifies the array in order to convert it to a single string; PowerShell stringifies an array by concatenating the elements with a single space as the separator by default; e.g.:[string] (1, 2) yields '1 2'.

Therefore, it's best to compose $str_msg as a string to begin with, with an explicit newline as the separator, e.g.:

$strMsg = "$file`r`n$([System.IO.File]::ReadAllText($file.FullName))"

Note the use of escape sequence "`r`n" to produce a CRLF, the Windows-specific newline sequence; on Unix-like platforms, you'd use just "`n" (LF).

.NET offers a cross-platform abstraction, [Environment]::NewLine, which returns the platform-appropriate newline sequence (which you could alternatively embed as $([Environment]::NewLine) inside "...").

An alternative to string interpolation is to use -f, the string-formatting operator, which is based on the .NET String.Format() method:

$strMsg = '{0}{1}{2}' -f $file,                         [Environment]::NewLine,                         [System.IO.File]::ReadAllText($file.FullName)


Cheers to the first answer

Backtick-r+backtick-n will do a carriage return with a new line in PS. You could do a Get-Content of your $file variable as a new array variable, and insert the carriage return at a particular index:

Example file: test123.txt

If the file contents were this:

line1line2line3

Store the contents in an array variable so you have indices

[Array]$fileContent = Get-Content C:\path\to\test123.txt

To add a carriage return between line2 and line3:

$fileContent2 = $fileContent[0..1] + "`r`n" + $fileContent[2]

Then output a new file:

$fileContent2 | Out-File -FilePath C:\path\to\newfile.txt

Hope this alternate approach helps future answer seekers


You need to use the carriage return powershell special character, which is "`r".

Use it like this to add a carriage return in your line :

$str_msg = $file,"`r",[System.IO.File]::ReadAllText($file.FullName);

Check this documentation to have more details on Poewershell special characters.