Note on the use of the backtick character at the end of PowerShell script lines
Posted: (EET/GMT+2)
PowerShell lets you split long commands across multiple lines using the backtick
character (`). It works, but it's easy to forget a hidden rule: the backtick
must be the last character on the line. Even a trailing space will make it unusable.
For example, this works:
Get-Process ` | Sort-Object CPU ` | Select-Object -First 10
But if you accidentally add a space after the backtick (for example to add a comment), PowerShell sees the line as complete:
Get-Process ` # trailing spaces break the continuation
I've run into this a few times, especially when editing scripts in editors that add whitespace "automagically". If your script suddenly throws unexpected token errors, check the trailing characters on your backtick lines.
As a personal rule, I now try to avoid backticks and instead use parentheses or pipeline alignment. These make the code read fairer and avoids subtle whitespace issues. But if you do use backticks, keep this rule in mind.