PowerShell is a command-line shell and scripting language that system administrators can use to automate tasks. One common task is outputting text with new lines and carriage returns. There are a few different ways to insert newlines and carriage returns in PowerShell:
- Using the `n newline character
- Using the `r carriage return character
- Using the Out-String cmdlet with -Width parameter
In this article, we will cover these methods in detail with examples to demonstrate how to output text with newlines and carriage returns in PowerShell scripts and at the interactive prompt.
`n Newline Character
The simplest way to insert a new line in PowerShell is to use the `n newline character.
For example:
"Line 1`nLine 2"
Will output:
Line 1 Line 2
The `n newline character tells PowerShell to insert a newline at that point in the string.
You can use this inline in strings for simple cases:
Write-Output "Hello`nWorld"
Outputs:
Hello World
Or you can use it with longer multiline strings:
$string = @" This is line 1 This is line 2`n This is line 3 "@ Write-Output $string
Outputs:
This is line 1 This is line 2 This is line 3
The `n character is interpreted as a newline whenever it appears in a double quoted string.
This makes it easy to insert newlines on the fly for simple text output in PowerShell.
`r Carriage Return
Similar to `n for newline, you can use `r in a string to insert a carriage return.
A carriage return moves the cursor position back to the beginning of the line without advancing to the next line.
Write-Output "Hello`rWorld"
This will output:
WorldHello
Note that the World overwrote the Hello text. This is because the `r moved the cursor position back to the start rather than advancing to a new line.
Carriage returns are used less frequently than newlines, but are helpful in some cases like returning to overwrite previous output.
As with newlines, you can use carriage returns inline in strings or with multiline strings:
$string = @" Hello`rOverwrite "@ Write-Output $string
Outputs:
OverwriteHello
So `r will return to the start of the current line.
Out-String -Width
The Out-String cmdlet has a -Width parameter that lets you specify the line width for text. This provides another way to insert newlines automatically based on a set width.
For example:
$string = "This is a long string that will wrap across multiple lines." $string | Out-String -Width 20
This will output:
This is a long string that will wrap across multiple lines.
By setting -Width to 20, Out-String inserted newlines at 20 character intervals to wrap the text.
You can use this for formatting any textual output to a certain width:
Get-Process | Out-String -Width 50
This formats the process output into 50 character wide strings.
The one catch with Out-String is that it converts input into a string. So you lose any objects and just get the text output. For formatting objects into a readable view, you may want to use Format-Table instead which maintains the object output.
Newlines in Functions and Scripts
The newline and carriage return characters work well for simple cases at the interactive prompt. But in advanced functions and scripts you often need more control over where newlines appear.
Here are some tips for handling newlines in PowerShell code:
Splatting
Use splatting with @ to split parameters across lines:
$params = @{ Name = "John" Age = 30 City = "New York" } Write-Output @params
Line Continuation
Use the backtick ` character to continue a statement on the next line:
$longVariableName = Get-ReallyReallyReallyLongVariable ` -AndSomeMoreParams ` -ThatWrapToNewLines
Line Breaks in Strings
Use newline and carriage return characters in multiline strings:
$string = "This is a long string with `nline breaks`rusing special characters."
Out-String
Use Out-String to set a specific width for text output:
Get-Process | Out-String -Width 100
Write-Output
Use multiple Write-Output statements to print separate lines:
Write-Output "Line 1" Write-Output "Line 2"
PowerShell Formatting Cmdlets
Use Format-Table, Format-List, Format-Wide to insert newlines in table, list and wide view formatting.
Examples
Here are some full examples putting these techniques together:
Multiline String
$string = @" Hello`rWorld`n Welcome to`n PowerShell! "@ Write-Output $string
Splatting + Multiline String
$params = @{ Message = @" Hi John,`n`n Your order has shipped! `n Let us know if you have any other questions. Thanks,`n The Company "@ To = "[email protected]" } Send-MailMessage @params
Out-String Formatting
Get-Process | Out-String -Width 50
Formats the process list into 50 character columns.
Conclusion
Newlines and carriage returns are essential for formatting text output in PowerShell. The key methods include:
– `n for newlines
– `r for carriage returns
– Out-String -Width for text wrapping
– Splatting and line continuation for multi-line statements
– Multiline strings with `n and `r
– Multiple Write-Output calls
– Formatting cmdlets like Format-Table
Using these features together gives you fine-grained control over text output in PowerShell scripts, functions and at the interactive prompt.
More Examples
Here are some additional examples to illustrate using newlines and carriage returns in PowerShell:
Newline in a Here-String
$string = @" Line 1 Line 2`n Line 3 "@
Carriage Return to Overwrite Output
Write-Output "Hello" Start-Sleep -Milliseconds 500 Write-Output "Hello`rWorld"
Out-String to Wrap Table
Get-Process | Format-Table | Out-String -Width 50
Newline in Format-Table
Get-Process | Format-Table Id, Name, CPU -AutoSize
Carriage Return in a Loop
1..5 | ForEach-Object { Write-Output $_ Start-Sleep -Milliseconds 500 Write-Output "`r" }
Frequently Asked Questions
Here are some common questions about working with newlines in PowerShell:
How do I insert a blank line between outputs?
Use two newline characters `n`n to insert a blank line:
Write-Output "Line 1`n`nLine 2"
What’s the difference between `n and `r?
`n is a newline that advances to the next line. `r is a carriage return that moves the cursor position to the start of the current line.
Can I use \n and \r like in other languages?
PowerShell uses the backtick notation for special characters in strings. So you need to use `n and `r rather than \n and \r.
How do I break a long line over multiple lines?
Use the backtick ` line continuation character:
$longVariable = Get-ReallyLongVariable ` -WithLotsOfParams ` -SplitAcrossLines
What’s the easiest way to format output to a certain width?
Use Out-String -Width to automatically wrap output at a set width:
Get-Process | Out-String -Width 50
Additional Examples
Here are some more examples to demonstrate using newlines and carriage returns in PowerShell:
Newlines in a Here-String
$string = @" Line 1 Line 2`n Line 3 "@
Carriage Return to Overwrite Previous Output
Write-Output "Hello" Start-Sleep -Milliseconds 500 Write-Output "Hello`rWorld"
Carriage Return in a Loop
1..5 | ForEach-Object { Write-Output $_ Start-Sleep -Milliseconds 500 Write-Output "`r" }
Multiline String with Special Characters
$string = @" Hello`rWorld`n Welcome to`n PowerShell! "@
Splitting Parameters Across Lines
$params = @{ Name = "Sarah" Age = 28 Address = "123 Main St`nNew York, NY 10025" }
Wrapping Table Output
Get-Process | Format-Table | Out-String -Width 50
Summary
To summarize, here are some best practices for handling newlines in PowerShell:
– Use `n for newlines and `r for carriage returns
– Splatting and backticks allow splitting statements over multiple lines
– Out-String -Width automatically wraps text to a set width
– Multiline strings give control over newlines in output
– Multiple Write-Output calls can print separate lines
– Format cmdlets like Format-Table insert newlines when formatting output
Following these tips will help ensure you have proper control over newline handling in scripts, at the prompt, and in any textual output from PowerShell.
Related Commands
Here are some other PowerShell commands related to string manipulation and output formatting:
Text Manipulation:
– Format-Table – Formats output as a table with newlines and columns
– Format-List – Formats output as a list with newlines
– Format-Wide – Formats output as a single line per object
– Out-String – Converts input objects into an output string
– -Join – Joins array elements into a string with a separator
– -Split – Splits a string into substrings based on a delimiter
String Handling:
– -replace – Replaces text in a string using regular expressions
– -like – Performs wildcard matching on a string
– -match – Matches a string against a regex pattern
– -f – Formats a string using placeholders
– Trim, TrimStart, TrimEnd – Removes whitespace
– ToUpper, ToLower – Change case
Output and Streams:
– Write-Output – Prints messages to the output stream
– Write-Host – Writes formatted text to the host
– Out-File – Sends output to a file
– Tee-Object – Outputs to screen and file
– Stream cmdlets (e.g. Out-String) – Manipulate output streams
Using these commands together with the newline and carriage return techniques covered here provides everything you need for full control over text output formatting in PowerShell.
Recommended Reading
For more information on working with newlines, strings and text output in PowerShell, refer to these resources:
– PowerShell in Action, 3rd Edition – Excellent book with in-depth coverage of PowerShell text handling and output formatting.
– Microsoft Docs – Official documentation for all PowerShell commands.
– PowerShell Explained Blog – Tips and tutorials for working with PowerShell strings, output and more.
– PowerShell.org – Community forums and articles on a wide range of PowerShell topics.
– PowerShell Pro Tools – Popular add-on with advanced string manipulation features.
– Using Out-String to Customize Text Output Blog Post – Examples of formatting with Out-String.
– An Introduction to PowerShell’s Output Streams Video – Explains how output streams work in PowerShell.
Taking the time to learn text manipulation and output formatting will dramatically improve your skills working with PowerShell. Mastering these techniques unlocks the full potential of PowerShell as a scripting and automation platform.
Summary
Here’s a quick summary of the key points covered in this article:
– Use `n for newlines and `r for carriage returns in strings
– Out-String -Width wraps text to a specified width
– Splatting with @ allows splitting parameters over multiple lines
– Backtick ` is the line continuation character in PowerShell
– Multiline strings give fine-grained control over newlines
– Format cmdlets like Format-Table insert newlines when formatting output
– Multiple Write-Output calls can be used to print separate lines
– Combine strings, splatting, and output formatting for full control over text output in PowerShell
With these techniques, you can handle newlines in any PowerShell output for scripts, functions, and interactive use.
Conclusion
Newlines and carriage returns are essential for formatting text output in PowerShell. By leveraging newlines characters, splatting, multiline strings, Out-String, and native output formatting cmdlets, PowerShell programmers have precise control over text output. Proper handling of newlines creates readable, user friendly output from scripts and functions.
The key points to remember are:
– Use `n and `r characters to insert newlines and carriage returns
– Splatting, backticks, and multiline strings allow splitting commands over multiple lines
– Out-String -Width parameter automatically wraps text to a specified width
– Format cmdlets like Format-Table insert newlines when formatting objects into tables or lists
– Multiple Write-Output calls can print separate lines
Combining these techniques provides full power over output formatting in PowerShell. Whether you need to format a simple string, output a cleanly formatted table, or ensure proper newlines in a complex script, these tools will help you handle any output with ease. Mastering PowerShell text manipulation opens up many possibilities for building professional grade scripts and tools.