PowerShell Splatting: Simplify and Organize Your Scripts (2024)

XFacebookLinkedIn

PowerShell splatting may sound strange, but this technique offers a convenient way to format and send arguments to cmdlets and functions. Instead of a long list of parameters or those same parameters separated by error-prone backticks, you can leverage splatting to make your code more readable and easier to use.

Not a reader? Watch this related video tutorial!

Not seeing the video? Make sure your ad blocker is disabled.

In this article, you’ll learn how best to use PowerShell splatting to enhance your scripts and code!

Prerequisites

If you’d like to follow along with this article, ensure you have Windows PowerShell 5.1 for most of the common functionality but PowerShell 7.1 to be able to override splatted parameters (demo below).

What is PowerShell Splatting?

To understand PowerShell splatting, you must first understand basic parameters. Typically, when you pass parameters to a command in PowerShell, you’d use a dash, the parameter name followed by the argument as shown below.

Alternatively, you could pass parameters using backticks as well.

Copy-Item `-Path "TestFile.txt" `-Destination "CopiedFile.txt" `-WhatIf `-Force

Why might you use the traditional method or the backtick method? The traditional method is fine, but with many parameters, this often becomes unwieldy to deal with and read. Using a backtick, “`, appears to give much better readability. This technique is usually not recommended due to the ease of forgetting or misplacing a backtick.

Instead, you can use PowerShell splatting. To splat a parameter set, first create a hashtable containing key/value pairs of each parameter and parameter argument. Then, once you have the hashtable built, pass that set of parameters to the command using @<hashtable name>.

For example, you can create a hashtable called $Params and then pass that set of parameters defined in the hashtable to the Copy-Item cmdlet as shown below.

$Params = @{ "Path" = "TestFile.txt" "Destination" = "CopiedFile.txt" "WhatIf" = $True "Force" = $True}Copy-Item @Params

Combining Traditional Parameters and Splatting

When you are testing scripts, or on the command-line, you can easily combine both methods. With scripts, it is often best to ultimately create a splatted variable to assign to the function or cmdlet. As an example of what this looks like is below:

$Params = @{ "Path" = "TestFile.txt" "Destination" = "CopiedFile.txt"}Copy-Item @Params -Force -WhatIf

As you can tell, this is a pretty useful technique where you don’t have to give up either method depending on your needs. Sometimes you may want to test an additional parameter or format the parameters differently for formatting by combining methods.

Overriding Splatted Parameters

In PowerShell 7.1, you can now override splatted parameters. Prior to this, you could not modify a splatted parameter via a passed parameter. As an example of overriding splatted parameters, notice how the -WhatIf parameter is overridden below.

$Params = @{ "Path" = "TestFile.txt" "Destination" = "CopiedFile.txt" "WhatIf" = $True "Force" = $True}Copy-Item @Params -WhatIf:$False
PowerShell Splatting: Simplify and Organize Your Scripts (1)

Overriding splatted parameters allows you to negate the key/value parameter defined in the hashtable and instead, use the value of the parameter defined traditionally.

Splatting Arrays for Positional Parameters

It’s considered best practice to use named parameters which forces you to specify the name of the parameter followed by the parameter argument. However, you can also splat parameters by position also.

If, for example, you’d like to copy a file called TestFile.txt to a file called CopiedFile.txt, you can do this using positional parameters like below.

Copy-Item 'TestFile.txt' 'CopiedFile.txt'

Instead of specifying positional parameters the old-fashioned way, you can also create an array (vs a hashtable as shown above) with only the parameter values. Below you’ll see an example of this.

$ParamArray = @( "TestFile.txt" "CopiedFile.txt")Copy-Item @ParamArray
PowerShell Splatting: Simplify and Organize Your Scripts (2)

Though this technique isn’t used quite often, this can be useful, as it is a less verbose method of providing splatted parameters. Remember that you will need to make sure you know the arguments’ positions in a given function or cmdlet; otherwise, you run the risk of passing values to incorrectly targeted parameters.

Proxy Functions and Splatted Commands

Sometimes, a PowerShell cmdlet doesn’t do quite what you need. In this case, you may choose to create a “wrapper” function or maybe even a proxy function. These functions allow you to add additional parameters to the original cmdlet and then call that cmdlet with the new parameters.

Understanding $Args and $PSBoundParameters

When you run a function in PowerShell, PowerShell creates an automatic array variable called $Args. This array contains all unnamed parameter values passed to that function.

You’ll find another automatic variable called $PSBoundParameters which contains a hashtable of all bound parameters. Notice below the Test-Function function that returns the $Param1 and $Param2 parameters.

Function Test-Function { Param( $Param1, $Param2 ) Write-Host "Unnamed Parameters" -ForegroundColor 'Green' $Args Write-Host "Bound Parameters" -ForegroundColor 'Green' $PSBoundParameters}Test-Function "test1" "test2" "test3" -Param1 "testParam" -Param2 "testParam2"
PowerShell Splatting: Simplify and Organize Your Scripts (3)

How are these automatic variables relevant to splatting? When you are building a proxy command, automatically passing in both bound and unbound parameters is very useful.

Building a Wrapper Function using Splatted Parameters

To show how useful splatting can be in wrapper functions, create a custom function that passes unnamed parameters and named parameters to the Copy-Item cmdlet. With this technique, you can quickly create custom functions that add additional functionality but retain the same parameter set you would expect.

Function Copy-CustomItem { Get-ChildItem Copy-Item @Args @PSBoundParameters Get-ChildItem}
PowerShell Splatting: Simplify and Organize Your Scripts (4)

It’s important to remember that if you use the CmdletBinding declaration or define parameter attributes, the automatic variable $Args no longer becomes available.

Conclusion

Splatting parameters to functions and cmdlets is an extremely useful technique for code readability and functionality. As it’s easy to manipulate hashtables and arrays, you can quickly expand upon splatted values to conditionally modify values depending on options that were passed. Incorporate this powerful technique into your scripts today!

PowerShell Splatting: Simplify and Organize Your Scripts (2024)

FAQs

How do you organize your PowerShell script? ›

Another tip for keeping track of your PowerShell scripts is to follow a consistent naming convention that reflects the purpose, function, and scope of your scripts. For example, you can use prefixes, suffixes, or keywords to indicate the type, category, or module of your scripts.

What example demonstrates splatting in PowerShell? ›

Example 1: Reuse splatted parameters in different commands

To change the colors of all commands, just change the value of the $Colors variable. The first command creates a hash table of parameter names and values and stores the hash table in the $Colors variable.

What is a good practice for scripting in PowerShell? ›

Avoid using spaces or special characters in your names and use PascalCase or camelCase conventions. Use the #Requires statement at the beginning of your script files and modules to specify the minimum version of PowerShell or any modules or snap-ins that they depend on.

How do I optimize a PowerShell script? ›

To improve your PowerShell scripts, you should use functions and modules to organize your code into reusable and modular units. Functions are blocks of code that perform a specific action and can accept input parameters and return output values.

What is the best way to run a PowerShell script? ›

In File Explorer (or Windows Explorer), right-click the script filename and then select Run with PowerShell. The Run with PowerShell feature starts a Windows PowerShell session that has an execution policy of Bypass, runs the script, and closes the session.

What is the correct structure for PowerShell commands? ›

Verb-Noun. Or, verbalized: PowerShell commands obey a Do-AThing structure, with a couple of effects: on the one hand, modular commands are easier to remember than individual commands themselves, on the other hand it allows cross inference and stretches the limit of known commands even further.

What are some cool things you can do with PowerShell? ›

It's still used for Windows task automation, but today, you can use it for tasks like:
  • Cloud management. PowerShell can be used to manage cloud resources. ...
  • CI/CD. It can also be used as part of a Continuous Integration/Continuous Deployment pipeline.
  • Automate tasks for Active Directory and Exchange.
Dec 18, 2023

What is splatting in rendering? ›

In computer graphics, texture splatting is a method for combining different textures. It works by applying an alphamap (also called a "weightmap" or a "splat map") to the higher levels, thereby revealing the layers underneath where the alphamap is partially or completely transparent.

How hard is PowerShell scripting? ›

Getting started with Microsoft PowerShell can be really easy, since the language is simple and you can easily get information about any cmdlet. But it's essential to also understand the systems you are interfacing with, so that your scripts do not lead to serious issues, such as system downtime or security incidents.

How do I plan a PowerShell script? ›

Method 1: Schedule PowerShell Script using Task Scheduler
  1. Open Task scheduler –> Task Scheduler Library –> Create Task.
  2. 2.In General tab, you can set scheduler name and description about the task like for what purpose the task has created. ...
  3. Switch to the Trigger tab and click the New button.
Aug 2, 2019

Why is PowerShell scripting important? ›

As a scripting language, PowerShell is commonly used for automating the management of systems. It's also used to build, test, and deploy solutions, often in CI/CD environments.

What makes PowerShell so powerful? ›

PowerShell uses a fileless approach that executes commands and scripts directly in memory, making it hard to detect. It can access nearly any Windows device by initiating a remote connection. Threat actors can leverage PowerShell using other malicious tools such as Empire, DeathStar and CrackMapExec.

What should I automate with PowerShell? ›

PowerShell can be used to automate tasks such as user management, CI/CD, managing cloud resources and much more. You'll learn to run commands, how to learn more about PowerShell and additionally to create and run script files.

How do you format a PowerShell script? ›

Formatting a PowerShell Script

Note: Workspace formatting settings are only used if you've opened the folder rather than an individual file. Press SHIFT+ALT+F (or press F1 and type Format and select Format Document). The code is now all well formatted, so save the document.

How do I sort in PowerShell? ›

You simply need to open a PowerShell window and start using the Sort-Object command. In the above syntax, -Property specifies the property or properties you want to sort by, and -Descending specifies whether you want to sort the data in descending order. The -Unique switch removes duplicate items from the result.

How to design a PowerShell script? ›

Creating a PowerShell Script
  1. Develop your script. ...
  2. Go to Admin > Scripts. ...
  3. On the PowerShell tab, click +Create New. ...
  4. Type the script name in the Name text box.
  5. Type a description in the Description text box.
  6. Click the Category dropdown list to select the type of script. ...
  7. Paste your script into the Script text box.

Top Articles
Latest Posts
Article information

Author: Dan Stracke

Last Updated:

Views: 5540

Rating: 4.2 / 5 (43 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Dan Stracke

Birthday: 1992-08-25

Address: 2253 Brown Springs, East Alla, OH 38634-0309

Phone: +398735162064

Job: Investor Government Associate

Hobby: Shopping, LARPing, Scrapbooking, Surfing, Slacklining, Dance, Glassblowing

Introduction: My name is Dan Stracke, I am a homely, gleaming, glamorous, inquisitive, homely, gorgeous, light person who loves writing and wants to share my knowledge and understanding with you.