我无法在 PowerShell 中将“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 提供了一种方法来做其他脚本语言可以做到的事情:我似乎找不到它......
最佳答案
PowerShell 在识别出不完整的语句时自动换行。对于比较操作,例如,如果您使用悬空运算符编写一行,就是这种情况:
if ( # Only do that when...
$foo -and # foo AND
$bar # bar
)
否则 PowerShell 会将这两行解析为两个不同的语句(因为第一行本身就是一个有效的表达式),而在第二行上失败,因为它是无效的。因此,您需要逃避换行符。
但是,仅在行中的某处放置一个转义字符是行不通的,因为这会转义下一个字符并保持换行符不变。
$foo ` # foo
将它放在带有(行)注释的行尾也不起作用,因为注释优先,将转义字符转换为文字字符。
$foo # foo`
如果要转义换行符,则需要将注释移到其他地方:
if (
# Only do that when foo AND bar
$foo `
-and $bar
)
或使用块注释作为 @Chard建议:
if ( # Only do that when...
$foo <# foo #> `
-and $bar <# AND bar #>
)
但坦率地说,我的建议是将操作符移到上一行的末尾,避免所有转义换行符的麻烦。
关于powershell - 如何在带有注释的多行行上拆分 "if"条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36689644/