Splat Me

I've recently become a big fan of splatting, which sounds awful until I explain it.

Don Jones

January 6, 2011

2 Min Read
ITPro Today logo in a gray background | ITPro Today

I've recently become a big fan of splatting, which sounds awful until I explain it.

In PowerShell, it's obviously very common to have parameters for your commands:

Get-EventLog -logName Security -newest 10
For longer commands, though, stacking up all of those parameters can be daunting - and make a script file pretty difficult to read. Look at the help for New-ADUser, for example, and imagine typing that command out, with all of its parameters - pretty big hunk of text.

Splatting offers an alternative. You create a hashtable that uses parameter names for keys, and parameter input for values. The way PowerShell parses these constructs means you can format them quite neatly within a script. When you're done, you just feed the hashtable (which you'll usually store in a variable) to the cmdlet:

$params = @{'logName'='Security';       'newest'=20}Get-EventLog @params
You need to be sensitive to punctuation, here:

  • The first use of params is preceded by a dollar sign, indicating that we want to access a variable with the name "params"

  • The second use of params DOES NOT have a dollar sign. Instead, it uses the @ splat operator to expand the contents of the variable.

A neat trick: You can mix and match, using splatted parameters in addition to normal ones, all with the same command.

This isn't a technique I use at the command-line much, but I'm using it more and more in scripts, because it makes script files a bit easier to read. I can nicely format all of the parameters in a hashtable, and then feed them to a command. It helps avoid line-wrapping and horizontal scrolling, both of which make a script harder to read and follow.

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like