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

后端 未结 3 1174
[愿得一人]
[愿得一人] 2021-01-17 17:45

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

If ( # Only do that when...
             


        
相关标签:
3条回答
  • 2021-01-17 17:53

    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.

    0 讨论(0)
  • 2021-01-17 17:55

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

    If ( <# Only do that when... #> `
        $foo <# foo #> `
        -and $bar <# AND bar #> 
    )
    {
        Write-Host foobar
    }
    
    0 讨论(0)
  • 2021-01-17 18:06

    This seems to work:

    if ( # Only do that when...
         ( $foo )-and   # foo AND
         ( $bar )       # bar
    )
     {Write-Host 'foobar'}
    
    0 讨论(0)
提交回复
热议问题