How to use Array Splatting in PowerShell?


Splatting is the method to pass the collection of parameters as a single unit so it will be easier for the command to read. Array splatting uses the splat values which do not require parameter names. The values must be in positional number order in the array.

We have a below copy example, in which we are copying one file from the source to the destination. Now we are not specifying the parameters here because we will use the positional parameter for the source path and the destination path.

If we check the help for those parameters, we will come to know their position.

For the source path.

help Copy-Item -Parameter path

Output

-Path <System.String[]>
Specifies, as a string array, the path to the items to copy. Wildcard characters are permitted.
Required?                      true
Position?                      0
Default value                  None
Accept pipeline input?         True(ByPropertyName, ByValue)
Accept wildcard characters?    true

If you check the Path parameter position is 0 so we can provide values without specifying a parameter in the first place. Similarly, the Destination parameter position is the second as shown below.

PS C:\> help Copy-Item -Parameter
Destination -Destination <System.String>
Specifies the path to the new location. The default is the current directory.
To rename the item being copied, specify a new name in the value of the Destination parameter.
Required?                       false
Position?                       1
Default value Current directory Accept pipeline input?       True (ByPropertyName)
Accept wildcard characters?     false

So we can directly use the command,

Copy-Item C:\Temp\10vms.csv 11vms.csv -Verbose

Now to splat the array value, we can combine those values into the array and we can pass to the Copy-Item command.

PS C:\> $items = "C:\Temp\10vms.csv","11vms.csv"
PS C:\> Copy-Item @items -Verbose

Likewise, if you have the parameter position at the 2 number, you can add it after a comma and so on.

Updated on: 18-Jan-2021

484 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements