Starting from Windows PowerShell 3.0, you can use “splatting”.
Splatting makes your commands shorter and scripts easier to read.
Splatting is a method of passing a collection of parameter values to a command as unit (using a hash table or an array).
Windows PowerShell associates each value in the collection with a command parameter.
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.
You can even re-use the splatting values in different command calls and use splatting to pass parameter values from the $PSBoundParameters automatic variable to other scripts and functions.
Splatting with hash tables
Use a hash table to splat parameter name and value pairs. You can use this format for all parameter types, including positional and named parameters and switch parameters.
Copy-Item -Path "test.txt" -Destination "test2.txt" –WhatIf
PS C:\>$HashArguments = @{ Path = "test.txt"; Destination = "test2.txt"; WhatIf = $true } PS C:\>Copy-Item @HashArguments
Splatting with arrays
Use an array to splat values for positional parameters, which do not require parameter names. The values must be in position-number order in the array.
Copy-Item "test.txt" "test2.txt" –WhatIf
PS C:\>$ArrayArguments = "test.txt", "test2.txt" PS C:\>Copy-Item @ArrayArguments -WhatIf
Making code more readable
Splatting is also very helpful to make your code shorter, but more importantly more readable.
If we apply some formatting the above example:
So is this new? No, I’m bringing it up again because it will be crucial in our next blog posts on advanced argument completers.
Hope this helps…
Related reading:
One thought on “Use the Power of PowerShell “Splatting””