Using Backticks
Use backticks to split multiline commands in PowerShell.
1 2 3 4 5 |
Get-ChildItem -Recurse ` -Filter *.md ` | Select LastWriteTime |
Usually, we get an automatic line continuation in PowerShell when the command can’t syntactically be complete.
However, if splitting a multiline command is required, then using backticks is preferred in such scenarios as presented above where too many operators are not involved; otherwise, it would be hard to read.
Remember not to have any character between backtick and line break; else, it will result in an error. For example: If you give space after backtick character, it won’t work.
Using Pipeline Operator
Use pipeline operator (|
) to split multiline command in PowerShell.
1 2 3 4 |
Get-ChildItem -Recurse -Filter *.md | Select LastWriteTime |
Using the pipeline operator is also a way to split the multiline command because, after the pipeline operator (|
), the command cannot be syntactically complete since it’s missing another pipeline element.
Using Specific Operators/Characters
To split multiline-command in PowerShell:
- Use pipeline operator
- Use comma
- Use all types of brackets
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Get-WmiObject -Class win32_logicaldisk | Format-Table DeviceId, @{ n="Size"; e={ [Math]::Round($_.Size/1GB,2) } }, @{ n="FreeSpace"; e={ [Math]::Round($_.FreeSpace/1GB,2) } } |
The opening and closing parentheses and commas also allow line continuation directly. See the above example code where we want to know free disk space details on our local machine.
A semicolon (;
) is used when we want to separate multiple commands.
Now the point is, why do we have to split the multiline command in PowerShell when it is producing the desired results?
This is important to achieve readability and easy to maintain because readable code can easily communicate its functionality to its users and help them to maintain it easily.
That’s all about multiline command in PowerShell.