如何拆分“ if”字段多行注释条件 [英] How to split an "if" condition over multiline lines with comments

查看:120
本文介绍了如何拆分“ if”字段多行注释条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
}

这会产生以下错误:


在'if'语句中的表达式后,缺少')'。

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

添加`字符无效:

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

我得到一个:


表达式或语句中出现意外的标记'#foo'。

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
}

但是我确信PowerShell提供了一种执行操作的方法其他脚本语言可以:我似乎找不到它...

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

推荐答案

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

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
)

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

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
)

或使用块注释作为 @Chard 建议:

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.

这篇关于如何拆分“ if”字段多行注释条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆