October 18th, 2010

Use Splatting to Simplify Your PowerShell Scripts

Summary: Use the Windows PowerShell 2.0 splatting technique to simplify your scripts. This step-by-step article provides the details.

 

Hey, Scripting Guy! Question Hey, Scripting Guy! I hope this is not a dumb question; I am a little hesitant to even ask, but something has been bugging me for over a month. I was recently in a Live Meeting with Scripting Guy Ed Wilson and he mentioned something that sounded like splatting. I searched the Windows PowerShell online help and could not find anything. I also searched the MSDN documentation and could not find anything either. What in the world is splatting—was he just being funny, or is that a real Windows PowerShell thing.

— JB

 

Hey, Scripting Guy! Answer Hello JB,

Microsoft Scripting Guy Ed Wilson here. I do quite a few Live Meetings, so I am not sure which meeting you were in with me. You are right; it would have been in passing, because I have not conducted a Live Meeting that covered only splatting. The topic of splatting has been mentioned a few times on the Hey, Scripting Guy! Blog, but we have not had anything in depth. Splatting is one of the great stealth features of Windows PowerShell 2.0. I decided to ask James Brundage to talk about Splatting.

James Brundage is the founder of Start-Automating (http://www.start-automating.com), a company dedicated to saving people time and money by helping them automate. Start-Automating offers Windows PowerShell training and custom Windows PowerShell and .NET Framework development. James formerly worked on the Windows PowerShell team at Microsoft, and he is the author of the PowerShellPack (http://code.msdn.microsoft.com/PowerShellPack ), a collection of Windows PowerShell scripts to enable building user interfaces, interact with RSS feeds, get system information, and more.

A Series on Splatting (and Stuff)

Part 1 – A Brief Introduction to Splatting

During my time on the Windows PowerShell team, I worked on a bunch of interesting, unsung parts of Windows PowerShell that can rock your scripting world. There are a few particular parts of Windows PowerShell with really funky names that, when combined together, can help you change the way you script.

The nifty areas are:

  • Splatting
  • Proxy Commands
  • Command MetaData

Splatting (the funkiest and least geeky of all of the names) is the ability to use a dictionary or a list to supply parameters to a command. Proxy commands are wrappers of existing commands in Windows PowerShell, and to make this possible, a number of different things had to be enabled in the language that can have interesting other uses. Command metdata provides information about the command and parameters of different commands, and provides a structure that you can use to “write” a command without typing out the whole script.

They all sound really boring, but they all open up tons of interesting doors. Let’s start by exploring what splatting can do:

Splatting is the ability to use a dictionary or a list to supply to parameters to a command. It sounds very, very boring, but it can start changing your scripting life really quickly. How? Well, if you’ve ever typed a lot of parameters into a command, you might notice that the lines start to get a little long and hard to read. In Windows PowerShell 1.0, you might add a backtick character to the line. Backtick characters (`) will make the line continue, but they’re hard to see and easy to forget. If you want to use a command with many parameters, such as Send-MailMessage without splatting, it would look like the following:

Send-MailMessage -To me@mydomain.com -From me@mydomain.com -Subject “Hi” `
   
-Body “Hello” -SmtpServer smpthost -ErrorAction SilentlyContinue

You can use splatting to separate the command from the parameters. This is shown here:

$MailMessage = @{
   
To = “me@mycompany.com”
   
From = “me@mycompany.com”
   
Subject = “Hi”
   
Body = “Hello”
   
Smtpserver = “smtphost”
   
ErrorAction = “SilentlyContinue”
}

Send-MailMessage @MailMessage

Personally, I find this a much nicer way to write scripts than using backtick characters, but it is very important to understand that the benefits of splatting go far beyond simply being able to write parameter input in a way that looks better.

Because you can use a hash table as the input to a function, it becomes pretty easy to use this technique to store commonly used function input, and to write functions that wrap other functions or join functions together.

First, let’s show how we can simply use hash tables as parameter presets. In this example, we’ll make a preset to display text in a control in Windows Presentation Foundation PowerShell Kit (WPK) with bold and italic text. If you do not have WPK, you can download it from http://code.msdn.microsoft.com/PowerShellPack.

Because we are going to use another part of the PowerShellPack later, let us start by importing the module:

Import-Module PowerShellPack

Now let’s define a simple style. To do this, we need to first create a hash table. The hash table is composed of a key and a value. In this example, the first key is FontWeight and the first value is Bold. The second key is FontStyle and the second value is Italic. Hash tables have been used many times in previous Hey, Scripting Guy! blog posts. The bold italic style definition is shown here:

$BoldItalic = @{
   
FontWeight = “Bold”
   
FontStyle = “Italic”
}

You can use splatting with regular parameter input, so now that I’ve defined a BoldItalic style, it’s possible to use this whenever I display a control. This shows the BoldItalic style applied to a label:

New-Label -Content “Hello World” @BoldItalic -AsJob

This uses the same style on a ListBox:

New-ListBox -ItemsSource (1..10) @BoldItalic -AsJob

Bold and italic are pretty simple. Let’s see how we can make this control fade in and out when the mouse moves over it. I normally put the styles I will use right inside the top-level control so that everything can use it. Make sure you notice that you can combine these styles. As you do more and more of this, you’ll start to build up styles that will work on almost any interface, and you can easily reuse these styles simply by copying and pasting:

New-StackPanel {
   
$HoverBehavior = @{
       
On_MouseEnter = {
           
$fadeIn = New-DoubleAnimation -From .75 -To 1 -Duration “0:0:0.25” 
           
Start-Animation -inputObject $this -animation $fadeIn -property ([Windows.Controls.Control]::OpacityProperty)
       
}
       
On_MouseLeave = {
           
$fadeOut = New-DoubleAnimation -From 1 -To .75 -Duration “0:0:0.25” 
           
Start-Animation -inputObject $this -animation $fadeOut -property ([Windows.Controls.Control]::OpacityProperty)
       
}
       
Opacity = .5
   
}
   
$BoldItalic = @{
       
FontStyle = “Italic”
       
FontWeight = “Bold”
   
}
   
New-Button “One” @BoldItalic @HoverBehavior
   
New-Button “Two” @HoverBehavior
} -asjob

Of course, you do not have to use this technique with something as advanced as WPK. You can easily use splatting to define common inputs for cmdlets you use every day. Let’s look at a few examples with Get-WmiObject. We will make some variables to define WMI queries, and we will use splatting to run them:

$LocalUsers = @{Query=“Select * From Win32_UserAccount WHERE LocalAccount=’true'”}
$ComputerSystem = @{Query=“Select * From Win32_ComputerSystem”}
$OperatingSystem = @{Query=“Select * From Win32_OperatingSystem”}

Let’s get the local users:

Get-WmiObject @LocalUsers

Now let’s get the computer system:

Get-WmiObject @ComputerSystem

Finally, let’s get the operating system:

Get-WmiObject @OperatingSystem 

An example of how to use splatting to make a complicated look and feel in WPK can be seen in the following image. The top item is being hovered over, and it’s bold and italic; the lower item is thin and faded out.

Image of splatting used to create complicated look and feel

 

JB, that is all there is to using splatting, which can make your life a little easier. Guest Blogger Week will continue tomorrow when James will talk about using splatting to write functions that call other functions.

We invite you to follow us on Twitter or Facebook. If you have any questions, send email to us at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

 

Ed Wilson and Craig Liebendorfer, Scripting Guys

Author

0 comments

Discussion are closed.