Powershell indent here-string

Viewed 2315

Does anybody know if it is possible to intend a here-string. Actually I've to write:

  $someString = @"
                First line
                second line
  "@

This becomes very ugly if you define a here-string on a deeper indentation level, because the ending "@ must be the first character on the line. Additionally somebody might "fix" the missing indentation and break the script ...

Is it possible to define a here-string like:

  $someString = @"
                First line
                second line
                "@

Thx

3 Answers

Late answer (technically "workaround"), I know, but this is currently one of the first search results for "PowerShell here-string indentation".

This becomes very ugly if you define a here-string on a deeper indentation level

I agree. For those of us concerned with the aesthetics of the resulting code, I found the following workaround on this TechNet question.

It's definitely not a here-string (especially since you must still escape embedded quotes), but at least for many multi-line use-cases, it will serve the same purpose, and allow you to keep indenting at the same level as the rest of the code-block:

$somestring = (
    "First line",
    "Second line"
) -join "`r`n"

To expand upon @NotTheDr01ds's answer, you can make it even more aesthetically pleasing by excluding commas after each item. So long as each item in the array is on its own line:

$HTML = @(
   "<h1>OIDC Services are <font style='color:green'>Online</font></h1>"
   "<br/><p>Your identity: <ul><li>Username: $($Context.User.Identity.Name)</li></ul></p>"
   "<br/><p>Troubleshooting: <ul><li><a href='/restart-service'>Restart Service</a></li></ul></p>"
) -Join "`n"
Related