powershellsyntaxline-continuation

Calling powershell single command in few lines


The below multistring powershell command:

(Get-Content "%FILE_PATH%") `
.Replace("      token1", "") `
.Replace("      token2", "") `
.Replace("      token3", "") | Set-Content "%FILE_PATH%" `

fails in first line with Replace:

    char:1
    + .Replace("      token1 ...
    + ~~~~~~~~
    Unexpected token '.Replace' in expression or statement.
        + CategoryInfo          : ParserError: (:) [], ParseException
        + FullyQualifiedErrorId : UnexpectedToken

but works if I put all lines in a single line (same failure behavior if I remove backticks). Given that a command is long, I want to put it into few lines. I also don't want introducing temporary variables.


Solution

  • The Backtick Character, Followed by New-Line-Character, is a White Space.

    According to the PowerShell Language Specification 3.0, Appendix B. Grammar, section B.1.3 White space, the backtick character, when at the end of a line, is a treated as a white space. This behavior applies to PowerShell versions 5.1 and PowerShell Core (7.x):

    whitespace:

    Any character with Unicode class Zs, Zl, or Zp
    Horizontal tab character (U+0009)
    Vertical tab character (U+000B)
    Form feed character (U+000C)
    ` (The backtick character U+0060) followed by new-line-character
    

    This means that you can use the backtick to break a command into multiple lines ONLY at locations in the command where a white space character is allowed by PowerShell.

    For example, since this is acceptable:

    'This is a test'. Replace('a ', 'a successful ')
    

    Then this is also acceptable:

    'This is a test'. `
    Replace('a ', 'a successful ')
    

    But, since this fails:

    'This is a test' .Replace('a ', 'a failed ')
    

    Then this will also fail:

    'This is a test'`
    .Replace('a ', 'a failed ')
    

    An alternative would be to use -Replace ... in place of .Replace(...):

    'This is a test'  `
    -Replace 'a ', 'a successful '