Home PowerShell Understanding PowerShell Splatting and How it Functions

Understanding PowerShell Splatting and How it Functions

Splatting in PowerShell may seem odd, but it’s a simple method to format and deliver parameters to functions and cmdlets.

A user may use splatting to make their code more legible and simpler to use instead of a lengthy list of arguments or the same old parameters delimited by error-prone backticks.

I’ll show you how to utilize PowerShell splatting to improve a user’s code and scripts in this post.

If you want to follow along with this post, make sure you have at minimum, Windows PowerShell 5.1 for most of the standard capabilities and PowerShell 7.1 for overriding splatted arguments.

Understanding PowerShell Splatting and How it Functions?

To comprehend PowerShell splatting, it is important to pay attention to the fundamental parameters. When passing parameters to a PowerShell command, users typically use a dash followed by the parameter name, and then the argument, as seen below.

Copy-Item -Path "TestFile1.txt" -Destination "CopiedFile1.txt" -WhatIf -Force

An alternative would be to use backticks to pass parameters as shown below:

Copy-Item ` 
    -Path "TestFile1.txt" ` 
    -Destination "CopiedFile1.txt" ` 
    -WhatIf ` -Force

The conventional way of providing parameters is great, but with numerous parameters, it quickly becomes cumbersome to work with and it could be hard to read and comprehend.

The use of a backtick, “`, seems to improve readability significantly. Due to the ease with which a backtick may be forgotten or misplaced, this method is generally not advised.

Instead, PowerShell splatting may be used. The process would involve creating a hashtable with key/value pairs for each parameter and creating the parameter argument. Then, after you’ve created the hashtable, use @<hashtable name> to give that set of arguments to the command.

As an example, you might construct a hashtable named $Vals and then use the Copy-Item cmdlet to provide that hashtable’s set of arguments to the Copy-Item cmdlet, as seen below.

$Vals = @{ 
  "Path" = "TestFile1.txt" 
  "Destination" = "CopiedFile1.txt" 
  "WhatIf" = $True 
  "Force" = $True 
} 

Copy-Item @Vals

Merging Conventional and Splatting Parameters

Users may simply mix the two techniques when testing scripts or while using the command line. When working with scripts, it’s common to construct a splatted variable for the purpose of assigning to the function or cmdlet. Here’s is what this could look like:

$Vals = @{ 
  "Path" = "TestFile.txt" 
  "Destination" = "CopiedFile.txt" 
} 

Copy-Item @Vals -Force -WhatIf

As the example shows, this is a really handy approach that allows users to a new alternative depending on their needs. By combining methods, users may test an extra parameter or structure the parameters differently for formatting.

How to Override Splatted Parameters

It is bow possible to override splatted arguments in PowerShell 7.1. Previously, users couldn’t use a passed argument to change a splatted parameter. Consider the splatted parameter overriding example below where I override the -WhatIf parameter.

$Vals = @{ 
  "Path" = "TestFile1.txt" 
  "Destination" = "CopiedFile1.txt" 
  "WhatIf" = $True 
  "Force" = $True 
} 

Copy-Item @Vals -WhatIf:$False

Overriding splatted arguments enables users to ignore the hashtable’s key/value parameter and instead use the value of the conventionally specified parameter.

Positional Parameters Splatting Arrays

Using named parameters is considered best practice since it requires you to provide the parameter name followed by a parameter argument. You may, however, splat parameters by location as well.

If users want to transfer a file named TestFile1.txt to a file called CopiedFile2.txt, for example, they may use positional arguments like the ones below.

Copy-Item 'TestFile1.txt' 'CopiedFile1.txt'

Users may construct an array (rather than a hashtable) using just the parameter values instead of providing positional arguments in an old-fashioned manner. You can see a model of this below.

$ValArray = @( 
  "TestFile1.txt" 
  "CopiedFile1.txt" 
) 

Copy-Item @ValArray

Though not often used, this approach may be helpful since it provides a less verbose way of supplying splatted arguments.

Keep in mind that you must be aware of the locations of the arguments in a particular function or cmdlet; otherwise, you risk sending data to improperly targeted parameters.

Splatted Commands and Proxy Functions

Often a PowerShell cmdlet isn’t exactly what you’re looking for. Users might construct a “wrapper” function or a proxy function in this situation.

These functions enable a user to add new arguments to an existing cmdlet before calling it with the new parameters.

Introducing $Args and $PSBoundParameters

When we execute a PowerShell script, it automatically generates an array variable named $Args. All unnamed argument values provided to the function are stored in this array.

Some other automated variable named $PSBoundParameters includes a hashtable containing the bound parameters. The Test-Function function will return the $ParamA and $ParamB arguments, as seen below.

Function Test-Function { 
  Param( 
    $ParamA, 
    $ParamB 
    ) 
  Write-Host "Unnamed Parameters" -ForegroundColor 'Green' 
  $Args 

  Write-Host "Bound Parameters" -ForegroundColor 'Green' 
  $PSBoundParameters 
} 

Test-Function "testA" "testB" "testC" -ParamA "testParam" -ParamB "testParam2"

powershell splatting

What role do automatic variables play in the splatting process? Automatically handling inbound and unbound arguments is extremely helpful when constructing a proxy command.

How to Use Splatted Parameters in Creating Wrapper Functions

Create a unique script that sends named and unnamed arguments to the Copy-Item cmdlet to demonstrate how beneficial splatting can be in wrapper functions. You may easily build new functions using this approach that provides extra functionality while keeping the same parameter set as before.

Function Copy-CustomItem { 
  Get-ChildItem 

  Copy-Item @Args @PSBoundParameters 

  Get-ChildItem 
}

It’s essential to keep in mind that when we make use of the CmdletBinding declaration or specify argument characteristics, the automatic variable $Args disappears.

📗FAQ📗

What is splatting in PowerShell?

In PowerShell, “splatting” refers to the technique of using the @ symbol to pass a dictionary of parameter names and values to a function or cmdlet as separate arguments.

This can make reading and writing long commands with many parameters easier, especially if the parameters are optional or you are setting a number of parameters to the same value.

Here’s an example of splatting in action:-

$params = @{
Path = ‘C:\Scripts\MyScript.ps1’
Verbose = $true
Confirm = $false
}
Start-Process @params

Instead of writing out the full command with all the parameter names and values like this:

Start-Process -Path ‘C:\Scripts\MyScript.ps1’ -Verbose $true -Confirm $false

You can use splatting to pass the parameters in a more concise way using the @params dictionary.

Remember that splatting only works with named parameters, and you must use the correct syntax when defining the splatting dictionary.

What does a splat variable in PowerShell begin with?

In PowerShell, splat variables begin with the @ symbol. The @ symbol is used to indicate that the following variable is a splatting variable, which is a dictionary of parameter names and values that will be passed to a function or cmdlet as separate arguments.

Here’s an example of how to use a splat variable in PowerShell:

$params = @{
Path = ‘C:\Scripts\MyScript.ps1’
Verbose = $true
Confirm = $false
}
Start-Process @params

In this example, $params is the splat variable, which is a dictionary containing three parameter names and values. The @params splat variable is then passed to the Start-Process cmdlet as separate arguments.

Remember that splatting only works with named parameters and must use the correct syntax when defining the splatting dictionary.

How to add to hashtable PowerShell?

In PowerShell, you can use the Add() method to add a new key-value pair to a hashtable.

Here’s an example of how to use the Add() method to add a new key-value pair to a hashtable:

$hashtable = @{}
$hashtable.Add(‘Key’, ‘Value’)
$hashtable

This will add a new key-value pair to the hashtable, with the key ‘Key’ and the value ‘Value’. You can then access the value by using the key like this:

$value = $hashtable[‘Key’]Write-Output $value

You can also use the [pscustomobject] type accelerator to create a hashtable in a single line, like this:

$hashtable = [pscustomobject]@{
Key1 = ‘Value1’
Key2 = ‘Value2’
}

This creates a hashtable with two key-value pairs, ‘Key1’ with a value of ‘Value1’, and ‘Key2’ with a value of ‘Value2’. You can then access the values using the keys like this:

$value1 = $hashtable.Key1
$value2 = $hashtable.Key2

How do I create a switch parameter in PowerShell?

In PowerShell, you can create a switch parameter by using the [switch] type accelerator in a function or script parameter. A switch parameter is a Boolean parameter that can either be on ($true) or off ($false).

Here’s an example of how to create a switch parameter in a function:

function MyFunction([switch]$Verbose) {
if ($Verbose) {
Write-Verbose ‘Verbose output is on’
}
}

You can then call the function and use the -Verbose switch to turn on verbose output:

MyFunction -Verbose

You can also specify a default value for the switch parameter, like this:

function MyFunction([switch]$Verbose=$false) {
if ($Verbose) {
Write-Verbose ‘Verbose output is on’
}
}

In this example, the $Verbose parameter will default to $false unless the -Verbose switch is specified when the function is called.

Keep in mind that switch parameters are always optional, and they do not take a value. They are used to turn a feature on or off.

Why $_ is used in PowerShell?

In PowerShell, the special variable $_ represents the current object in the pipeline. It can be used in commands that operate on the current object, such as in a foreach loop or when working with the Where-Object cmdlet.

Here is an example of using $_ in a foreach loop:

foreach ($object in $objects) {
# Do something with the current object
$_ | Some-Command
}

In this example, the foreach loop iterates over the $objects collection and sets the value of $_ to the current object in the collection on each iteration. The command Some-Command is then executed with the current object as its input.

You can also use $_ in the script block of a Where-Object cmdlet to filter the objects in a pipeline based on some condition:

$objects | Where-Object { $_.Property -eq ‘Value’ }

This will pass only the objects in $objects that have a Property equal to 'Value' to the next command in the pipeline.

What does @{} represent in PowerShell?

In PowerShell, @{} is used to create a hashtable. A hashtable is a collection of key-value pairs that are organized based on the hash of the key. It is similar to a dictionary in other programming languages.

What is $$ in PowerShell?

In PowerShell, $$ represents the last token of the last line received by the interpreter. It is often used in scripts to refer to the current line being executed.

What does @{ mean in PowerShell?

In PowerShell, @{} is used to create a hashtable. A hashtable is a collection of key-value pairs that are organized based on the hash of the key. It is similar to a dictionary in other programming languages.

Last Thoughts On Powershell Splatting

Splatting arguments into procedures and cmdlets are a great way to improve the readability and usefulness of your code.

Because hashtables and arrays are simple to handle, users can rapidly expand on splatted data to conditionally change values based on the parameters provided. Include this effective approach in your scripts right now!