Adding a newline (line break) to a Powershell script

Question:

I have a script I am running in Powershell, and I want to be able to put a line in my resulting text file output between the ccript name and the script content itself.

Currently, from the below, the line $str_msg = $file,[System.IO.File]::ReadAllText($file.FullName) is what I need, but I need a line to separate $file and the result of the next expression. How can I do this?

Answer:

  • $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.:

Note the use of escape sequence "rn" 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:

Source:

Adding a newline (line break) to a Powershell script by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply