Add a New Line to Command Output in PowerShell

Rohan Timalsina Feb 17, 2022
  1. Use ``n` to Add a New Line to Command Output in PowerShell
  2. Using Out Field Separator OFS in PowerShell
  3. Using [Environment]::NewLine in PowerShell
Add a New Line to Command Output in PowerShell

PowerShell includes a set of special character sequences that can customize the output content. The sequences are commonly known as escape sequences. They begin with the backtick character `` ` and are case-sensitive.

Some examples of escape sequences are `0, `a, `b, `e, `f`, `n, `r, etc. Escape Sequences is only interpreted when enclosed in double-quotes " ".

This article will discuss the different ways of adding a new line to command output in PowerShell.

Use ``n` to Add a New Line to Command Output in PowerShell

The ``n` character inserts a new line or line break after the character in the output.

Write-Host "This tutorial teaches you to add`na new line in PowerShell."

Output:

This tutorial teaches you to add
a new line in PowerShell.

You can use multiple ``n` characters to add multiple lines.

Write-Host "This tutorial`nteaches you to add`n`n`nmultiple lines in PowerShell."

Output:

This tutorial
teaches you to add


multiple lines in PowerShell.

Using Out Field Separator OFS in PowerShell

The Out Field Separator OFS allows you to specify the character to separate the elements of an array. The valid values are strings, so the elements should be converted to strings.

First, you must define a separator in the OFS variable. You have to set double `n as the separator to add a single line.

$OFS="`n`n"
$color = 'red', 'blue', 'green', 'yellow'
"$($color)"

Output:

red

blue

green

yellow

Using [Environment]::NewLine in PowerShell

You can also use the [Environment]::NewLine object to add a new line to the command output.

$new = [Environment]::NewLine
$color | ForEach {"$_$new"}

Output:

red

blue

green

yellow

Another example of using [Environment]::NewLine with Sort-Object. The Sort-Object cmdlet helps sort objects by property values in ascending or descending order.

The following command gets the name of all installed programs on the computer, adds a new line to each program’s name, and sorts it.

$new = [Environment]::NewLine
Get-ChildItem HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall | ForEach{ $_.GetValue("DisplayName")} | Sort-Object | ForEach{"$_$new"}

Output:

Tools for .Net 3.5

AnyDesk

ASUS Aac_NBDT HAL

ASUS AURA Display Component

ASUS AURA Headset Component

ASUS Framework Service

ASUS Framework Service
Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website