Add a New Line in Powershell

PowerShell includes different options for formatting console output. This article will discuss four methods of adding a new line in the PowerShell output.

The first method explains how to use PowerShell newline characters to break a string across lines of the console.

The second and third methods discuss how to write each element of an array in a new line of the console output.

The last method covers how to break a string at the position of a given string or any position of your choice.

Method 1: Using the New Line Character

PowerShell’s newline character is “n" - a backtick followed by the letter "n". The backtick symbol is on the same key as the tilde character (~).

The "n” newline character is equivalent to the “\n” in Python, C++, and Java programming languages.

You can also use multiple newline characters to get multiple line breaks on the string.

We can also concatenate strings with “n".

Output:

This is the first stringThis is the second string

Output:

This is the first string
This is the second string

Method 2: Using Output Field Separator (OFS)

The preference $OFS variable specifies a character that separates the elements of an array when the array is converted into a string.

Once we define the $OFS variable, elements of The PowerShell array will be joined on the defined $OFS value. Let's see some examples.

Output:

pencil#book#Dubai#LAX

We can then use the newline character to break the array elements across lines.

Output:

pencil
book
Dubai
LAX

Method 3: Using System.Environment.NewLine Property

This is a utility allows newline character to be added to the output on Unix platforms.

Output:

pencil
book
Dubai
LAX

Method 4: Using str.replace() Function to Break a String on a Given Character

If we want to break a string at a given character, we can replace that given character with a newline character. Here is an example

Output:

this is string 1
 this is string 2
 this is string 2

We can also use string formatting on PowerShell. In the following example, we use {i} as a placeholder for the i+1 value on the format list; therefore, {0} matches the first characters on the format list, that is, "%%" and the second placeholder, {1} is filled with two newline characters (n`n).

Output:

This is %% a long
 string

Conclusion

This article discusses how to add a new line in PowerShell. We discussed four methods on how to break a string across output console lines. In these methods, we also covered how to write each element of an array in a new line.