Submitting Parameters through Splatting

by Jun 3, 2014

Splatting was introduced in PowerShell 3.0, but many users still never heard of this. It is a technique to programmatically submit parameters to a cmdlet. Have a look:

$infos = @{}
$infos.Path = 'c:\Windows'
$infos.Recurse = $true
$infos.Filter = '*.log'
$infos.ErrorAction = 'SilentlyContinue'
$infos.Remove('Recurse')

dir @infos 

This example defines a hash table with key-value pairs. Each key corresponds to a parameter found in the dir command, and each value is the argument that should be submitted to that parameter.

Splatting can be extremely useful if your code needs to decide which parameters should be forwarded to a given cmdlet. Your code would then simply manipulate a hash table, then submit it to the cmdlet of choice.

Twitter This Tip! ReTweet this Tip!