What is this here-string people are talking about?

When long strings need to be generated it could sometimes be cumbersome to keep adding strings together, especially if you want the string to contain several lines, tabs and special characters. Here-string can solve that problem and is very easy to use.
String
Lets first look at a simple example of how regular strings work with variables, new lines and tabs. After that we look at an example of how to use here-string instead to make the code easier to read.

PowerShell here-string

The following code example generates a regular string with seven lines including special characters and variables.
$x = 'Hello'

$y = 'World'
$str = "#This is the first line`n`nx = $x`ny = $y`n`n"
$str += "`tYou can even use`"quotes`"!`nThis is the seventh line"
Write-Host $str
Console output: string
Even if this example is very simple it can quickly get cluttered things like "`n" and "`t" in the string so that is one of the things we want to get rid of with here-string.
Here-strings starts with the @ symbol and ends with the @ symbol. The first line must contain only the @ symbol and a quote and the last line must have first a quote and then the @ symbol, like this:
$str = @"
This is my string. There are many like it, but this one is mine.
"@
Putting it together it might look like this:
$x = 'Hello'
$y = 'World'
$str = @"
#This is the "first" line

x = $x
y = $y

    You can even use "quotes"!
#This is the seventh line
"@
Write-Host $str
This give the same output as the first example. As you can see I don't need to use "`n" for new lines and no "`t" for tabs so the code is a bit easier to read. Even quotes are accepted in the middle of the string so all that clutter is gone. This can be extra useful if you want to generate html pages. If you have tried PowerShell Web Server you might have noticed that its using here-strings quite a lot when generating HTML pages and now you know why.

No comments

Post a Comment