Here's a quick little fun fact about working with here-strings in Powershell. If you're not sure what here-strings are, they are a regular string surrounded by @ symbols. Here-strings are most commonly used to create multi-line strings (normal strings always end up on a single line).
If you're creating here-strings in the console it's pretty straight forward. You simply type @"
and press [Enter]
then type your first line press [Enter]
type the second line, [Enter]
and so on with the last line being the closing "@
. Pretty simple right? Where things get tricky however is when you are writing an actual Powershell script.
We'll start with something simple, I'll have a basic "if" statement that, if it evaluates to true it writes one set of lines and if it's false it writes another:
$i = 2
if($i = 2){
@"
Can it be true...
...that two equals two?
"@
} else { @"
Subtract one from this thought...
...and equal it does not!
"@
}
This should work perfectly fine right? It's all nicely formatted and looks great. Well, unfortunately it won't work. If you were to copy and paste this code into Powershell and press [Enter]
you'll find that it continues to expect another line. Likewise, if you run this as part of a script, the script will halt at this point. Powershell treats the ending "@
as part of the string and thereby ignores it. Unfortunately typing it again just continues to add to the string and the only way to stop it is to escape out of the command thereby canceling it. In order to get this to work the correct way, you need to make sure that the here-string resides on the far left with no spaces or indents like so:
$i = 2
if($i = 2){
@"
Can it be true...
...that two equals two?
"@
} else { @"
Subtract one from this thought...
...and equal it does not!
"@
}
This code, while not quite as pretty, will work every time. Reason being is that we took out the indentation on the here-string.
Now, in this little example removing the indentation isn't really a big deal as we're only going down one level however, in more complex scripts where you may be 5 or 6 or more levels deep, having to place all of your here-strings to the far left can make your script downright confusing to anybody even yourself. In these cases it may be prudent to place your here-strings in their own variables and then just call them whenever you need them. Alternately, you can bypass here-strings all together and use regular double-quote strings combined with the `n
trick to create new lines as needed.