Making PoSH cleaner, one iteration at a time.
Have you ever looked at a long-winded PowerShell command and thought,“There’s gotta be a better way to write this mess…”?
Let me introduce or maybe re-introduce you to the often overlooked, yet delightfully helpful little trick called splatting. No, it’s not the sound your coffee makes when it hits the floor (though I’ve experienced that tragedy too). It’s a way to clean up your scripts and make them more readable, especially when your coffee spilled all over the floor at 6 AM (Because it’s your first cup and motor functions aren’t quite online).
So, what’s a splat?
In PowerShell, a splat combines all of your parameters into one rich, aromatic blend using a hashtable or array, and then passes it directly into your command. Instead of dumping a chaotic mix of ingredients into your script like a rushed a Monday morning I’m late for work and there’s traffic on the highway to-go cup of jitter juice, you’re dispensing a perfectly crafted order that is neat, labeled, and easy to sip.
The coffee references are “strong” today.
Example Time: Send-MailMessage (With and Without Splatting)
A commonly used command that I have written many times over the years is Send-MailMessage in order to craft and send an email from a on-premise server. Here’s what it might look like without a splat:
Send-MailMessage -From '[email protected]' -To '[email protected]' -Subject 'Weekly Report' -Body 'All systems operational!' -SmtpServer 'smtp.company.com' -Priority High -DeliveryNotificationOption OnSuccess, OnFailure
Man… that’s a lot. I will admit, most of my scripts from back in the day look like this. So what would it look like if we used a “shot” of experience.
$emailParams = @{
From = '[email protected]'
To = '[email protected]'
Subject = 'Weekly Report'
Body = 'All systems operational!'
SmtpServer = 'smtp.company.com'
Priority = 'High'
DeliveryNotificationOption = 'OnSuccess','OnFailure'
}
Send-MailMessage @emailParams
Whoah, that looks “bold”. You can easily read and replace the command variables.
Why Use Splats?
They look cool! What else do you need to know…? Fine, here are some more reasons to use a splat.
- Cleaner Code – Your eyes and future self will thank you.
- Easy Contributions – It’s easier for others to follow the logic.
- Reusable – Pass the same splat to multiple times.
- Less Typing – Because who has time to type -DeliveryNotificationOption more than once?
Final Thoughts
Next time you’re writing PowerShell, take a step back and review your code. Find that one command that you wrote at 1 AM on a Thursday morning after getting in the zone and ask yourself: “Is this going to be a “tall” order for others to read?” It’s amazing what you will find after a fresh pot of perspective…. and sleep.
Stay clean. Stay clever. And splat away friends.
P.S. – This post was brought to you by caffeine.
P.S.S. – You already knew that….