3 Approaches to Powershell Multiliners — Backticks, Splatting, and Natural Line Continuators

Pavol Kutaj
2 min readJan 6, 2021

--

usecase

  • the question is that of an elegant interaction, i.e. not having to write long commands in a single line
  • the answer is don’t use backticks unless splitting arguments, try splatting and rely on natural line continuators like a pipeline operator or scriptblock operator (and many others)

1. backtick

  • a cmdlet ` Get-ChildItem -Path $env:windir -Filter *.dll -Recurse` can be made a little more readable by breaking up long lines with PowerShell’s escape character:
  • backtick is the escape character in powershell
PS C:\> Get-ChildItem `
-Path $env:windir `
-Filter *.dll `
-Recurse

In general, the community feels you should avoid using those backticks as “line continuation characters” when possible.

Readability · PowerShell Practice and Style

  • hard to read
  • easy to miss
  • easy to mistype

1.1. when to use backtick

  • when needing to split line into several cmdlet arguments
  • not piping
  • not using script blocks
  • …but say copying the content of an entire folder (files and subfolders)
  • this is just for the “personal hygiene”, not communicating with another person (this is not code, this is an interactive shell where I just communicate with myself)
PS C:\Users\Admin> copy -Path .\source\repos\dataIntoArray\ `
>> -Destination .\Documents\workspace\c#\dataIntoArray\ `
>> -Recurse `
>> -Force `
>> -Verbose

2. splatting

  • splatting means passing parameters bound via a hash table to command with @ operator
$GetWmiObjectParams = @{
Class = "Win32_LogicalDisk"
Filter = "DriveType=3"
ComputerName = "SERVER2"
}
Get-WmiObject @GetWmiObjectParams

3. natural line continuation

These are parts of the PowerShell language that naturally allow you to continue on to the next line without any special character or consideration.

Bye Bye Backtick: Natural Line Continuations in PowerShell

  • highly compatible with K&R indentation / 1TBS
  • in the following, I am utilizing SCRIPTBLOCK OPERATOR {} and PIPELINE OPERATOR |
PS C:\Users\Admin\Downloads> dir |
>> sort LastWriteTime -Descending |
>> select -First 3 |
>> % {
>> mi $_.FullName "C:\Users\Admin\Documents\Zoom\2185596"
>> }
  • I am just copying the last 3 downloaded files into its ticket-folder

4. sources

--

--

No responses yet