Moerwald
Moerwald

Reputation: 11284

Powershell indent here-string

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

Upvotes: 6

Views: 4595

Answers (3)

Unknown Variable
Unknown Variable

Reputation: 99

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"

Upvotes: 1

NotTheDr01ds
NotTheDr01ds

Reputation: 20734

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"

Upvotes: 3

Dimse
Dimse

Reputation: 1506

The closing "@ must be at the start of the line.

I agree with you that this can make the script file harder to read, but it is the rule, and there is no way around it as far as I know.

You can find a uservoice entry here, and you should vote for it if you feel this is important to you. It does not look like a priority at the moment, with only 3 votes, but the more votes, the higher the priority for the powershell team to look into it.

Upvotes: 5

Related Questions