如何在带有注释的多行行上拆分 "if" 条件

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

我无法在 PowerShell WITH 注释中将 "if" 条件拆分为多行,参见示例:

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

这会产生以下错误:

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

添加 ` 字符无效:

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

我得到一个:

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

我找到的唯一方法是删除评论:

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

但我确信 PowerShell 提供了一种方法来完成其他脚本语言可以做的事情:我似乎找不到它...

您可以使用块注释 <# Your Comment #> 来执行此操作。

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

PowerShell 在识别出不完整的语句时自动换行。对于比较操作,如果例如您写了一行带有悬空运算符的行,就会出现这种情况:

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

否则 PowerShell 会将这两行解析为两个不同的语句(因为第一行本身就是一个有效的表达式)并且在第二行上失败,因为它是无效的。因此你需要转义换行符。

但是,仅在行中的某处放置一个转义字符是行不通的,因为那样会转义下一个字符并保持换行符不变。

<strike>$foo ` # foo</strike>

将它放在带有 (line) 注释的行的末尾也不起作用,因为注释优先,将转义字符变成文字字符。

<strike>$foo  # foo`</strike>

如果你想避开换行符,你需要将评论移到别处:

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

或按照 建议使用块注释:

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

但坦率地说,我的建议是将运算符移到上一行的末尾,避免转义换行符的所有麻烦。

这似乎有效:

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