Powershell: Splatting

Some notes on the method of “splatting” in Powershell code.

Splatting is a method of passing a collection of parameter values to a command as an unit.
Splatting makes your commands shorter and easier to read.

Splatted parameter values are stored in named splatting variables, which look like standard variables, but begin with an at symbol (@) instead of a dollar sign ($).

The at symbol (@) tells PowerShell that you are passing a collection of values, instead of a single value.

Example 1: Named parameters via hashtable

$HashArguments = @{ Path = "test.txt"; Destination = "test2.txt"}

Copy-Item @HashArguments -WhatIf

Which resolves to Copy-Item -Path "test.txt" -Destination "test2.txt" -WhatIf

Example 2: Positional parameters via array

$ArrayArguments = "test.txt", "test2.txt"

Copy-Item @ArrayArguments -WhatIf

Example 3: Switch parameter

param ([switch] $X)
        
if ($X) { $AdditionalArguments = @{CaseSensitive = $true } }
else    { $AdditionalArguments = @{CaseSensitive = $false} }

"Foo Bar Baz" | select-string -pattern "bar" @AdditionalArguments | % { $_.Matches.Value }
Some remarks on this (based on https://stackoverflow.com/a/58508387/17589673):
In most cases, omitting a switch like -Foo and passing it with value false (i.e. -Foo:$false, note the colon!) is equivalent.
However, commands could detect the difference and sometimes act differently.

One notable example is the common parameter -Confirm, also a switch parameter: Omitting it means that the $ConfirmPreference preference variable is respected, whereas -Confirm:$false means that the preference variable should be overridden (and confirmation should not be requested).

If you want to make this distinction yourself in a PowerShell script or function, you can call $PSBoundParameters.ContainsKey('Foo') in addition to checking the $Foo (-Foo) switch parameter variable’s value.