How to split the if condition into multi-line comment lines

I can’t get the if condition to split across multiple lines in PowerShell WITH comments, see example:

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

This causes the following error:

There is no closing ')' after the expression in the 'if' expression.

Adding the ` character does not work:

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

I get:

Unexpected token `` # foo '' in expression or expression.

The only way I found is to remove the comments:

 If ( ` $foo ` -and $bar ` ) { Write-Host foobar } 

But I'm sure PowerShell offers a way to do what other scripting languages ​​can use: I just can't find it ...

+6
source share
3 answers

PowerShell automatically wraps lines when it recognizes an incomplete instruction. For comparison operations, this is the case if, for example, you write a line with a hanging 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 in itself) and will not execute in the second because it is invalid. Thus, you need to avoid line breaks.

However, simply placing the escape character somewhere in the string will not work, because it will avoid the next character and leave the string unchanged.

 $foo ` # foo 

Putting the comment at the end of the line (line) will also not work, because the comment takes precedence, turning the escape character into a literal character.

 $foo # foo` 

If you want to avoid line breaks, 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 :

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

But honestly, my recommendation is to move the statement to the end of the previous line and avoid all the problems associated with line breaks.

+5
source

You can use the comments of the <# Your Comment #> block for this.

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

It works:

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

All Articles