about_Splatting - PowerShell (2024)

  • Article

Short description

Describes how to use splatting to pass parameters to commands in PowerShell.

Long description

Splatting is a method of passing a collection of parameter values to a commandas a unit. PowerShell associates each value in the collection with a commandparameter. Splatted parameter values are stored in named splatting variables,which look like standard variables, but begin with an At symbol (@) insteadof a dollar sign ($). The At symbol tells PowerShell that you are passing acollection of values, instead of a single value.

Splatting makes your commands shorter and easier to read. You can reuse thesplatting values in different command calls and use splatting to pass parametervalues from the $PSBoundParameters automatic variable to other scripts andfunctions.

Beginning in Windows PowerShell 3.0, you can also use splatting to representall parameters of a command.

Syntax

<CommandName> <optional parameters> @<HashTable> <optional parameters><CommandName> <optional parameters> @<Array> <optional parameters>

To provide parameter values for positional parameters, in which parameter namesare not required, use the array syntax. To provide parameter name and valuepairs, use the hash table syntax. The splatted value can appear anywhere in theparameter list.

When splatting, you do not need to use a hash table or an array to pass allparameters. You may pass some parameters by using splatting and pass others byposition or by parameter name. Also, you can splat multiple objects in a singlecommand so you don't pass more than one value for each parameter.

As of PowerShell 7.1, you can override a splatted parameter by explicitlydefining a parameter in a command.

Splatting with hash tables

Use a hash table to splat parameter name and value pairs. You can use thisformat for all parameter types, including positional and switch parameters.Positional parameters must be assigned by name.

The following examples compare two Copy-Item commands that copy the Test.txtfile to the Test2.txt file in the same directory.

The first example uses the traditional format in which parameter names areincluded.

Copy-Item -Path "test.txt" -Destination "test2.txt" -WhatIf

The second example uses hash table splatting. The first command creates a hashtable of parameter-name and parameter-value pairs and stores it in the$HashArguments variable. The second command uses the $HashArgumentsvariable in a command with splatting. The At symbol (@HashArguments) replacesthe dollar sign ($HashArguments) in the command.

To provide a value for the WhatIf switch parameter, use $True or $False.

$HashArguments = @{ Path = "test.txt" Destination = "test2.txt" WhatIf = $true}Copy-Item @HashArguments

Note

In the first command, the At symbol (@) indicates a hash table, not asplatted value. The syntax for hash tables in PowerShell is:@{<name>=<value>; <name>=<value>; ...}

Splatting with arrays

Use an array to splat values for positional parameters, which do not requireparameter names. The values must be in position-number order in the array.

The following examples compare two Copy-Item commands that copy the Test.txtfile to the Test2.txt file in the same directory.

The first example uses the traditional format in which parameter names areomitted. The parameter values appear in position order in the command.

Copy-Item "test.txt" "test2.txt" -WhatIf

The second example uses array splatting. The first command creates an array ofthe parameter values and stores it in the $ArrayArguments variable. Thevalues are in position order in the array. The second command uses the$ArrayArguments variable in a command in splatting. The At symbol(@ArrayArguments) replaces the dollar sign ($ArrayArguments) in thecommand.

$ArrayArguments = "test.txt", "test2.txt"Copy-Item @ArrayArguments -WhatIf

Using the ArgumentList parameter

Several cmdlets have an ArgumentList parameter that is used to passparameter values to a script block that is executed by the cmdlet. TheArgumentList parameter takes an array of values that is passed to thescript block. PowerShell is effectively using array splatting to bind thevalues to the parameters of the script block. When using ArgumentList, ifyou need to pass an array as a single object bound to a single parameter, youmust wrap the array as the only element of another array.

The following example has a script block that takes a single parameter that isan array of strings.

$array = 'Hello', 'World!'Invoke-Command -ScriptBlock { param([string[]]$words) $words -join ' ' } -ArgumentList $array

In this example, only the first item in $array is passed to the script block.

Hello
$array = 'Hello', 'World!'Invoke-Command -ScriptBlock { param([string[]]$words) $words -join ' '} -ArgumentList (,$array)

In this example, $array is wrapped in an array so that the entirearray is passed to the script block as a single object.

Hello World!

Examples

Example 1: Reuse splatted parameters in different commands

This example shows how to reuse splatted values in different commands. Thecommands in this example use the Write-Host cmdlet to write messages to thehost program console. It uses splatting to specify the foreground andbackground colors.

To change the colors of all commands, just change the value of the $Colorsvariable.

The first command creates a hash table of parameter names and values and storesthe hash table in the $Colors variable.

$Colors = @{ForegroundColor = "black"; BackgroundColor = "white"}

The second and third commands use the $Colors variable for splatting in aWrite-Host command. To use the $Colors variable, replace the dollar sign($Colors) with an At symbol (@Colors).

#Write a message with the colors in $ColorsWrite-Host "This is a test." @Colors#Write second message with same colors. The position of splatted#hash table does not matter.Write-Host @Colors "This is another test."

Example 2: Forward parameters using $PSBoundParameters

This example shows how to forward their parameters to other commands usingsplatting and the $PSBoundParameters automatic variable.

The $PSBoundParameters automatic variable is a dictionary object(System.Collections.Generic.Dictionary) that contains all the parameter namesand values that are used when a script or function is run.

In the following example, we use the $PSBoundParameters variable to forwardthe parameters values passed to a script or function from Test2 function tothe Test1 function. Both calls to the Test1 function from Test2 usesplatting.

function Test1{ param($a, $b, $c) "a = $a" "b = $b" "c = $c"}function Test2{ param($a, $b, $c) #Call the Test1 function with $a, $b, and $c. Test1 @PSBoundParameters #Call the Test1 function with $b and $c, but not with $a Test1 -b $PSBoundParameters.b -c $PSBoundParameters.c}Test2 -a 1 -b 2 -c 3
a = 1b = 2c = 3a =b = 2c = 3

Example 3: Override splatted parameters with explicitly defined parameters

This example shows how to override a splatted parameter using explicitlydefined parameters. This is useful when you don't want to build a new hashtableor change a value in the hashtable you are using to splat.

The $commonParams variable stores the parameters to create virtual machinesin the East US location. The $allVms variable is a list of virtual machinesto create. We loop through the list and use $commonParams to splat theparameters to create each virtual machine. However, we want myVM2 to becreated in a different region than the other virtual machines. Instead ofadjusting the $commonParams hashtable, you can explicitly define theLocation parameter in New-AzVm to supersede the value of the Locationkey in $commonParams.

$commonParams = @{ ResourceGroupName = "myResourceGroup" Location = "East US" VirtualNetworkName = "myVnet" SubnetName = "mySubnet" SecurityGroupName = "myNetworkSecurityGroup" PublicIpAddressName = "myPublicIpAddress"}$allVms = @('myVM1','myVM2','myVM3',)foreach ($vm in $allVms){ if ($vm -eq 'myVM2') { New-AzVm @commonParams -Name $vm -Location "West US" } else { New-AzVm @commonParams -Name $vm }}

Example 4: Using multiple splatted objects in a single command

You can use multiple splatted objects in a single command. In this example,different parameters are defined in separate hashtables. The hashtables aresplatted in a single Write-Host command.

$a = @{ Message = 'Hello', 'World!'}$b = @{ Separator = '|'}$c = @{ BackgroundColor = 'Cyan' ForegroundColor = 'Black'}Write-Host @a @b @c

Splatting command parameters

You can use splatting to represent the parameters of a command. This techniqueis useful when you are creating a proxy function, that is, a function thatcalls another command. This feature is introduced in Windows PowerShell 3.0.

To splat the parameters of a command, use @Args to represent the commandparameters. This technique is easier than enumerating command parameters andit works without revision even if the parameters of the called command change.

The feature uses the $Args automatic variable, which contains all unassignedparameter values.

For example, the following function calls the Get-Process cmdlet. In thisfunction, @Args represents all the parameters of the Get-Process cmdlet.

function Get-MyProcess { Get-Process @Args }

When you use the Get-MyProcess function, all unassigned parameters andparameter values are passed to @Args, as shown in the following commands.

Get-MyProcess -Name PowerShell
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName------- ------ ----- ----- ----- ------ -- ----------- 463 46 225484 237196 719 15.86 3228 powershell
Get-MyProcess -Name PowerShell_Ise -FileVersionInfo
ProductVersion FileVersion FileName-------------- ----------- --------6.2.9200.16384 6.2.9200.1638... C:\Windows\system32\WindowsPowerShell\...

You can use @Args in a function that has explicitly declared parameters. Youcan use it more than once in a function, but all parameters that you enter arepassed to all instances of @Args, as shown in the following example.

function Get-MyCommand{ Param ([switch]$P, [switch]$C) if ($P) { Get-Process @Args } if ($C) { Get-Command @Args }}Get-MyCommand -P -C -Name PowerShell
 NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 50 112.76 78.52 16.64 6880 1 powershellPath : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exeExtension : .exeDefinition : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exeSource : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exeVersion : 10.0.22621.3085Visibility : PublicOutputType : {System.String}Name : powershell.exeCommandType : ApplicationModuleName :Module :RemotingCapability : PowerShellParameters :ParameterSets :HelpUri :FileVersionInfo : File: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe InternalName: POWERSHELL OriginalFilename: PowerShell.EXE.MUI FileVersion: 10.0.22621.1 (WinBuild.160101.0800) FileDescription: Windows PowerShell Product: Microsoft&reg; Windows&reg; Operating System ProductVersion: 10.0.22621.1 Debug: False Patched: False PreRelease: False PrivateBuild: False SpecialBuild: False Language: English (United States)

Notes

If you make a function into an advanced function by using either theCmdletBinding or Parameter attributes, the $args automatic variableis no longer available in the function. Advanced functions require explicitparameter definition.

PowerShell Desired State Configuration (DSC) was not designed to use splatting.You cannot use splatting to pass values into a DSC resource. For moreinformation, see Gael Colas' article Pseudo-Splatting DSC Resources.

See also

  • about_Arrays
  • about_Automatic_Variables
  • about_Hash_Tables
  • about_Parameters
about_Splatting - PowerShell (2024)
Top Articles
Grayscale Dumping Bitcoin Holdings? Here’s Why | Bitcoin Market | CryptoRank.io
Gudetama
Sdn Md 2023-2024
Dairy Queen Lobby Hours
Robot or human?
Unitedhealthcare Hwp
Google Jobs Denver
Rondale Moore Or Gabe Davis
Lost Ark Thar Rapport Unlock
Paketshops | PAKET.net
Urinevlekken verwijderen: De meest effectieve methoden - Puurlv
My.doculivery.com/Crowncork
Spelunking The Den Wow
Athens Bucket List: 20 Best Things to Do in Athens, Greece
Pro Groom Prices – The Pet Centre
No Strings Attached 123Movies
Flower Mound Clavicle Trauma
Dr Manish Patel Mooresville Nc
Tcu Jaggaer
Praew Phat
Effingham Bookings Florence Sc
The best firm mattress 2024, approved by sleep experts
Pokemon Unbound Shiny Stone Location
Popular Chinese Restaurant in Rome Closing After 37 Years
Pecos Valley Sunland Park Menu
The Tower and Major Arcana Tarot Combinations: What They Mean - Eclectic Witchcraft
Canvasdiscount Black Friday Deals
Ou Football Brainiacs
Hwy 57 Nursery Michie Tn
Ryujinx Firmware 15
Experity Installer
Deepwoken: Best Attunement Tier List - Item Level Gaming
Issue Monday, September 23, 2024
Craigslist Maryland Baltimore
Www Craigslist Com Shreveport Louisiana
Gabrielle Enright Weight Loss
Ark Unlock All Skins Command
Metro 72 Hour Extension 2022
Jefferson Parish Dump Wall Blvd
Muziq Najm
Game8 Silver Wolf
Stanford Medicine scientists pinpoint COVID-19 virus’s entry and exit ports inside our noses
Convenient Care Palmer Ma
Lake Kingdom Moon 31
Crigslist Tucson
Advance Auto.parts Near Me
Lebron James Name Soundalikes
Quest Diagnostics Mt Morris Appointment
Gelato 47 Allbud
Dumb Money Showtimes Near Regal Stonecrest At Piper Glen
Latest Posts
Article information

Author: Barbera Armstrong

Last Updated:

Views: 6223

Rating: 4.9 / 5 (59 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Barbera Armstrong

Birthday: 1992-09-12

Address: Suite 993 99852 Daugherty Causeway, Ritchiehaven, VT 49630

Phone: +5026838435397

Job: National Engineer

Hobby: Listening to music, Board games, Photography, Ice skating, LARPing, Kite flying, Rugby

Introduction: My name is Barbera Armstrong, I am a lovely, delightful, cooperative, funny, enchanting, vivacious, tender person who loves writing and wants to share my knowledge and understanding with you.