How to split an “if” condition over multiline lines with comments

£可爱£侵袭症+ 提交于 2019-12-19 16:48:15

问题


I cannot achieve to split an "if" condition over multiple lines in PowerShell WITH comments, see example:

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

This generates the following error:

Missing closing ')' after expression in 'if' statement.

Adding the ` character does not work:

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

I get a:

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

The only way I've found is to remove the comments:

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

But I am sure PowerShell offers a way to do what others scripting languages can: I just seem cannot find it...


回答1:


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.




回答2:


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

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



回答3:


This seems to work:

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


来源:https://stackoverflow.com/questions/36689644/how-to-split-an-if-condition-over-multiline-lines-with-comments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!