How to Remove Newlines from a String in PowerShell (Multiline to One Line)

To remove newlines from a string in PowerShell, replace them with the -replace operator and the pattern \r?\n, which matches both Windows and Unix line breaks:

$oneLine = $text -replace '\r?\n', ' '

In this tutorial, I’ll show you how to remove newlines from a string in PowerShell and how to convert a multiline string to a single line without leftover spaces.

You’ll also clean file content, collapse blank lines and build a reusable function.

See the hidden characters first

Newlines are invisible, which makes them hard to debug. This small helper shows them as \r and \n, and most examples below start with it:

function Show-Hidden ($Text) { $Text -replace "`r", '\r' -replace "`n", '\n' }

Windows ends lines with \r\n (carriage return and line feed). Linux, macOS and many web APIs use just \n. Text that passed through several systems often has both, as finding carriage returns in a string shows.

Replace newlines with -replace

This address has one Windows line break and one Unix line break. \r?\n catches both, because the \r is optional:

function Show-Hidden ($Text) { $Text -replace "`r", '\r' -replace "`n", '\n' }

$address = "1200 Main Street`r`nSuite 400`nAustin, TX 78701"
"Before: $(Show-Hidden $address)"

$oneLine = $address -replace '\r?\n', ', '
"After:  $oneLine"

Output:

Before: 1200 Main Street\r\nSuite 400\nAustin, TX 78701
After:  1200 Main Street, Suite 400, Austin, TX 78701
PowerShell remove newline from string
Both kinds of line break become commas (PowerShell 7)

Replace with an empty string, ”, to join the lines with nothing in between. Use a comma or space when the words would otherwise run together.

What is a multiline string in PowerShell?

A multiline string is one string value that contains line breaks. The easiest way to write one is a here-string: @” on its own line, the text, then “@ at the very start of the last line.

The double-quoted form expands variables, while the single-quoted form @’ … ‘@ keeps every character as typed:

$city = 'Seattle'
$literal = @'
Ship to: $city
Status: "Pending"
'@
$expanded = @"
Ship to: $city
Status: "Pending"
"@
$literal
$expanded
"Lines in the here-string: $(($expanded -split '\r?\n').Count)"

Output:

Ship to: $city
Status: "Pending"
Ship to: Seattle
Status: "Pending"
Lines in the here-string: 2

Quotation marks inside a here-string need no escaping, which is why it’s popular for JSON, HTML and email bodies.

A regular string can hold line breaks too, either with the `n escape or by pressing Enter inside the quotes. For adding breaks rather than removing them, see adding a new line to a string.

Convert a multiline string to a single line

This contact card has an indented line and a doubl