Like many other high-level languages, PowerShell gives us the ability to preserve line breaks, tabs, whitespace, and other text formatting with the here-string. I'm going to be looking how you create and use a here-string in PowerShell.

Many other languages use the here-string, and it is not PowerShell specific. Other languages call the here-string by a different name: here-document, here-text, heredoc, and hereis to name a few. Unix shells like bash and zsh first used here-documents. Languages such as PHP, Python, and Ruby have also adopted their own "here-document."

Here-string syntax ^

To define a here-string in PowerShell, you need to use the @ character followed by either a single or double quote and then a newline. To end, close the quotes and add another @ on a newline, so it looks like:

@"
"@
Here string example start

Here string example start

Once you have created this here-string enclosure, you are free to add newlines, symbols, and text formatting, with no restriction on the amount of text written. PowerShell uses the .NET System.String type, which represents text as a sequence of UTF-16 code units. The advantage to using 16-bit Unicode is that it has a character set capable of encoding all 1,112,064 valid code points. So you can use characters from every language in the world!

Here-strings may be either literal (single-quoted) or expanding (double-quoted), just like regular strings in .NET. If you use single quotes with the here-string, it will not expand any variables and subexpressions. The best use for the single quote option is for string text not required to change.

Using the here-string ^

We have spoken about the history of the here-string and how it works. Now is a good time to see some working examples using the here-string in PowerShell.

We now know the here-string can preserve the formatting. Here is an example of this:

$formatText = @'
This
    is
      showing
             text
                 formatting!
'@
$formatText
Preserved formatting with here string

Preserved formatting with here string

In this example, we used a literal here-string. Here is a something a bit more interesting, the expanding here-string:

$name = "Graham"
$HereString = @"
My name is $name.
I live in the 'UK'.
The current date is: `n`t$(Get-Date)
"@
$HereString
Expanding here string example

Expanding here string example

I set a variable $name outside the here-string and added to the first line inside the here-string to show variable expansion. The second line demonstrates the use of a literal string and lastly the use of a subexpression to get the current date and time. I added the date and time to a newline with a tab indentation by using the escape characters `n and `t.

Another useful technique for the here-string is the redirection to a file. By either piping to Out-File or using the redirection operator >, you can create a script or text file:

 @'
param([string]$name)
"Hello $name!"
'@ > hello.ps1
Using redirection to create files

Using redirection to create files

Following from the previous example of creating code files from a here-string, you can also perform code generation while preserving the code formatting. I've used the here-string in this example with the Add-Type cmdlet to generate a small C# class:

Add-Type -TypeDefinition @"
    public class SimpleCsharpExample {
        public static int Add(int n1, int n2) {
        return n1 + n2;
        }
    }
"@
[SimpleCsharpExample]::Add(1,2)
Creating C# by using a here string

Creating C# by using a here string

The TypeDefinition parameter of Add-Type allows me to use a here-string containing my C# code. The C# code itself is a simple class that uses a static method to add two numbers together.

Subscribe to 4sysops newsletter!

Although very simple, the here-string is a flexible and useful way to work with larger blocks of text. The examples I've shown in this article give some good cases of how you can use the here-string in your PowerShell code.

avatar
2 Comments
  1. Michael 1 year ago

    Great article!  Quick question, "How do I tab over the last @ in the here-string?"  Without this ability to tab over, it breaks PowerShell ISE and Visual Studio Code's PowerShell extension.  In other words, the expand and collapse functionality of code blocks is broken, because those IDE's don't know how to handle the '@ starting at any other location than the beginning of a line.

  2. Derek 9 months ago

    Hey just a quick comment in unix a here doc and here sting are two similar but distinctly different forms of redirection with differnt uses and behavior some examples you can avoid quote recursion with a heredoc, the limitstring of a heredoc makes it less suitable to being piped out on the command line as it needs its own line by itself to close, using escapes you can run a batch of commands based on conditional patamiters wirh multiple if statemnts or nested loops herestings can redirect vairiables comand output and arrays with patamiter sibstition in a way that lets you cheat order of interpolation. Heredocs can read from a file that was populated but not synced during a running script and feed that data back into the top level process for re-evaluation. But love your page ive found more usefull information here than some of the books ive read 🙂

Leave a reply

Please enclose code in pre tags

Your email address will not be published. Required fields are marked *

*

© 4sysops 2006 - 2022

CONTACT US

Please ask IT administration questions in the forums. Any other messages are welcome.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account