How to split an "if" condition over multiline lines with comments How to split an "if" condition over multiline lines with comments powershell powershell

How to split an "if" condition over multiline lines with comments


PowerShell automatically wraps lines when it recognizes an incomplete statement. For comparison operations this is the case if for instance you write a line with a dangling operator:

if ( # Only do that when...    $foo -and  # foo AND    $bar       # bar)

Otherwise PowerShell will parse the two lines as two different statements (because the first line is a valid expression by itself) and fail on the second one because it's invalid. Thus you need to escape the linebreak.

However, just putting an escape character somewhere in the line won't work, because that will escape the next character and leave the linebreak untouched.

$foo ` # foo

Putting it at the end of a line with a (line) comment also won't work, because the comment takes precedence, turning the escape character into a literal character.

$foo  # foo`

If you want to escape the linebreaks you need to either move the comment elsewhere:

if (    # Only do that when foo AND bar    $foo `    -and $bar)

or use block comments as @Chard suggested:

if ( # Only do that when...    $foo       <# foo #> `    -and $bar  <# AND bar #>)

But frankly, my recommendation is to move the operator to the end of the previous line and avoid all the hassle of escaping linebreaks.


You can use block comments <# Your Comment #> to do this.

If ( <# Only do that when... #> `    $foo <# foo #> `    -and $bar <# AND bar #> ){    Write-Host foobar}


This seems to work:

if ( # Only do that when...     ( $foo )-and   # foo AND     ( $bar )       # bar) {Write-Host 'foobar'}