How and Why to Use Splatting (passing [switch] parameters)

On our internal discussion list, someone just asked about how to pass switch parameters from one function to another.  This person asked this as "Why can’t [switch] parameters be passed as parameters?".

My short answer was simple: "They Can Be"

Answering this question is a great way to illustrate the value of a PowerShell V2 feature called Splatting.  Splatting is two things, it’s a way to get all of the parameters passed to a function automatically (they’re in a variable, $psBoundParameters), and it’s a way to take a list or dictionary of arguments and pass them on to the next function below.

The mistake of trying to pass along a switch parameter is a pretty easy one to make.  [switch] will let you specify the parameter by just passing –ParameterName instead of –ParameterName True.

When you try to pass on a value to another underlying function, –SwitchParameterInOtherFunction $switchParameterInThis function will set the switch to true in the underlying function, and then pass a positional parameter with the value of the switch parameter.

The V1 fix for this is to put a : between the parameter name and its value.  The V2 fix for this is to simply use splatting.   The important line below is in bold and italics.

V2: V1:

function test2($x, $y, [switch]$passThru) {
    "In Test 2"
    "x:"
    $x
    "y:"
    $y
    "passThru:"
    $passThru
}

function test1($x, $y, [switch]$passThru) {
    "In Test 1"
    Test2 @psBoundParameters
}

test1 "a" "b" -passThru

function test2($x, $y, [switch]$passThru) {
    "In Test 2"
    "x:"
    $x
    "y:"
    $y
    "passThru:"
    $passThru
}

function test1($x, $y, [switch]$passThru) {
    "In Test 1"
    Test2 -x:$x -y:$y -passThru:$passThru
}

test1 "a" "b" -passThru

So why use splatting?  Well, here was my answer to the question on our PowerShell Discussions alias:

Notice that with @psBoundParameters, I don’t have to specify the parameters on by one.   This is both more convenient (less typing) and less error prone (less chance of forgetting a parameter or adding a typo).

To see more powerful examples of splatting, you can check out Get-CommandPlugin and the CodeDownloader module.

Hope this Helps,

James Brundage [MSFT]