r/PowerShell • • Apr 05 '19

PowerShell tricks: Splatting

https://blog.destruktive.one/powershell-tricks-splatting/
150 Upvotes

58 comments sorted by

View all comments

27

u/si1ic0n_gh0st Apr 05 '19

Splatting doesn't sound all that cool, until you realize that you can use it to vary what arguments you pass to a cmdlet/program. To build on Destruktive's example, there might be times where you don't want to set OpenPorts or maybe sometimes you'll need to also add PublicIpAddressName.

With splatting you can dynamically build your arguments, then hand them off to whatever you are trying to execute. Really cleans up your code.

5

u/destruktive Apr 05 '19

It can really help when doing automation based on conditions and I might actually write an example of that in the future.

I wrote this just because I wanted to get people to write cleaner code ;)

3

u/si1ic0n_gh0st Apr 05 '19

I use it quite a bit in a script where I'm passing arguments off to a wrapper I use for WinSCP. There are all sorts of different arguments you might need to pass based on protocol or authentication requirements (SSH key auth for instance). Splatting makes this fairly easy to accomplish.

1

u/xenaprincesswarlord Apr 06 '19

Can you please eli5?im learning to code now I never even heard of splat

4

u/lolinux Apr 06 '19

Splatting is basically creating a hashtable where you will hold all of the parameters that you will use for a future command. If you read the original post, you might have noticed that the keys of the hashtable are the names of the arguments, and the values of the hashtable are the values that will be passed to the cmdlet. The only caveat is that when you actually call the cmdlet, you will have to prepend an @ not just an $, like with normal variables.

1

u/xenaprincesswarlord Apr 06 '19

I see. Seems smart actually!

1

u/destruktive Apr 06 '19

Have an exam in a couple of hours but I can write something later today 🤓

1

u/xenaprincesswarlord Apr 06 '19

Today, tomorrow it’s fine!