Using Splatting for Better Formatting

by Jun 1, 2012

Supplying parameters to a cmdet often results in very long lines like this one:

Get-ChildItem -Path $env:windir -Filter *.ps1 -Recurse -ErrorAction SilentlyContinue -Force

It lists all PowerShell files located anywhere in your Windows folder.

In listings, long lines can become hard to read, and when you publish code, part of the line may get cut off. Traditionally, you could break up long lines in multiple parts using PowerShell's cumbersome escape character:

Get-ChildItem -Path $env:windir `
-Filter *.ps1 -Recurse `
-ErrorAction SilentlyContinue -Force

However, this approach is error-prone. First, the escape character itself is so small it may get lost when others type in your code. Second, this only works if no additional character follows an escape character. Even a simple space character right after an escape character will mess up the line break.

A much more robust way is to use splatting to submit a large number of parameters to a cmdlet:

$MyParameter = @{
    Path = "$env:windir"
    filter = '*.ps1'
    Recurse = $true
    ErrorAction = 'SilentlyContinue'
    Force = $true
}

Get-ChildItem @MyParameter 

As a nice side effect, you can submit your set of parameters defined in $MyParameter multiple times. Splatting consists of a hash table ($MyParameter) that is submitted via '@' to a cmdlet. Each key in your hash table turns into a parameter, and each value becomes the parameter argument. For switch parameters like -Force or -Recurse, you explicitly set the key to $true or $false.

Twitter This Tip! ReTweet this Tip!