Splatting and Default parameters

One thing you don’t hear much about is default parameters.

Consider this

Get-CimInstance -ClassName Win32_LogicalDisk -Filter “DeviceId = ‘C:'”

A pretty standard use of CIM.

Now think if you have to do this across a number of machines on a regular basis.  Typing could get a bit tedious.

You could use splatting:

$params = @{
  ClassName = ‘Win32_LogicalDisk’
  Filter = “DeviceId = ‘C:'”

Get-CimInstance @params

Create a hash table of parameter names and values and use that to reduce your typing. Because its a hash table you can modify as required to use other classes or Filters

An alternative is to use default parameters

$PSDefaultParameterValues = @{
‘Get-CimInstance:ClassName’ = ‘Win32_LogicalDisk’
‘Get-CimInstance:Filter’ = “DeviceId = ‘C:'”


Use the $PSDefaultParameterValues variable to hold your default values. Note how the cmdlet and parameter are defined. You can then call the cmdlet and the default parameters and their values are applied.

If you want to override the default values you may have to do it for all of the default values for a cmdlet – in the above case the Filter is nonsensical if applied to Win32_OperatingSystem so you’d have to do this

Get-CimInstance -ClassName Win32_OperatingSystem -Filter “Manufacturer LIKE ‘%'”

Used with a bit of care splatting and default parameters are a good way to save typing

This entry was posted in Powershell Basics. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s