It sounds like something that should pop up on the TV while watching a rerun of the 1960s Batman TV series. Its not though.
Splatting is another way of passing parameters to commands. This command shouldn’t come as a surprise.
Get-ChildItem -Path "c:\test" –Recurse
We can also pass the parameters like this
001
002 003 004 005 |
$params = @{
Path = "c:\test" Recurse = $true } Get-ChildItem @params |
Create a hash table of your parameters using parameter name and value pairs. Recurse is switch parameter so we need to set it to $true.
We then use Get-ChildItem @params to run the command. Notice the @ symbol rather than a dollar. This is the splat operator and it splats (sends) the values to the parameters.
This also works for our own functions. Lets create a simple function
001
002 003 004 005 006 007 008 009 010 011 012 013 014 |
function testsplat {
[CmdletBinding()] param ( [string]$comment, [int]$first, [int]$second, [string]$action ) switch ($action){ times {"$comment $($first * $second)"} add {"$comment $($first + $second)"} } } |
We have four parameters and depending on the value of the action parameter we multiply or add. Not very sophisticated but it demonstrates what we are doing.
We can run the function and use it like this
testsplat -comment "Answer is" -first 12 -second 3 -action add
testsplat -comment "Answer is" -first 12 -second 3 -action times
and we will get the expected results
Answer is 15
Answer is 36
We can splat the parameter values
$params = @{
comment = "Splat Answer is"
first = 12
second = 3
action = "add"
}
testsplat @params
and get the expected result
Splat Answer is 15
because we are dealing with a hash table we can simply change one parameter
$params["action"] = "times"
testsplat @params
and get
Splat Answer is 36
Where this will really work for me is testing functions. I can put this together to give me a simple way of testing.
001
002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 |
function testsplat {
[CmdletBinding()] param ( [string]$comment, [int]$first, [int]$second, [string]$action ) switch ($action){ times {"$comment $($first * $second)"} add {"$comment $($first + $second)"} } } $params = @{ $params ["action"] = "times"testsplat @params ###################################################### |
I can store my parameters in a hash table and change parameters as I wish. if I want to rerun the tests I have all of my previous tests effectively documented. The row of ### symbols is just to draw attention to the results when I use ISE.
Splatting looks like it is going to make my testing easier.