Home Tech Understanding PowerShell Splatting and How it Functions

Understanding PowerShell Splatting and How it Functions

0

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.

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!