CDu*_*Duv 8 powershell comments if-statement conditional-statements
我无法实现在PowerShell WITH comments 中将多个行拆分为"if"条件,请参阅示例:
If ( # Only do that when...
$foo # foo
-and $bar # AND bar
)
{
Write-Host foobar
}
Run Code Online (Sandbox Code Playgroud)
这会生成以下错误:
在'if'语句中表达后缺少关闭')'.
添加`角色不起作用:
If ( ` # Only do that when...
$foo ` # foo
-and $bar ` # AND bar
)
{
Write-Host foobar
}
Run Code Online (Sandbox Code Playgroud)
我得到一个:
表达式或语句中出现意外的标记"#foo".
我找到的唯一方法是删除评论:
If ( `
$foo `
-and $bar `
)
{
Write-Host foobar
}
Run Code Online (Sandbox Code Playgroud)
但我确信PowerShell提供了一种方法来完成其他脚本语言的工作:我似乎找不到它......
PowerShell在识别出不完整的语句时会自动换行.对于比较操作,例如,如果您使用悬空运算符编写一行:
if ( # Only do that when...
$foo -and # foo AND
$bar # bar
)Run Code Online (Sandbox Code Playgroud)
否则PowerShell会将这两行解析为两个不同的语句(因为第一行本身就是一个有效的表达式),而第二行则失败,因为它无效.因此,您需要逃避换行.
但是,只是将一个转义字符放在行中的某个位置将不起作用,因为这将逃脱下一个字符并保持换行不变.
$foo ` # fooRun Code Online (Sandbox Code Playgroud)
将它放在带有(行)注释的行的末尾也不起作用,因为注释优先,将转义字符转换为文字字符.
$foo # foo`Run Code Online (Sandbox Code Playgroud)
如果你想逃避换行,你需要将评论移到其他地方:
if (
# Only do that when foo AND bar
$foo `
-and $bar
)
Run Code Online (Sandbox Code Playgroud)
或者使用@Chard建议的块注释:
if ( # Only do that when...
$foo <# foo #> `
-and $bar <# AND bar #>
)
Run Code Online (Sandbox Code Playgroud)
但坦率地说,我的建议是将运营商移到上一行的末尾,避免所有逃避换行的麻烦.