The benefit of splatting is most obvious when working with commands that expect a larger number of parameters.
This first example uses the Windows PowerShell module ScheduledTasks to create a fairly basic task that runs once a day at midnight:
$taskAction = New-ScheduledTaskAction -Execute pwsh.exe -Argument 'Write-Host "hello world"'
$taskTrigger = New-ScheduledTaskTrigger -Daily -At '00:00:00'
Register-ScheduledTask -TaskName 'TaskName' -Action $taskAction -Trigger $taskTrigger -RunLevel 'Limited' -Description 'This line is too long to read'
It is possible to spread the command out, in an attempt to make it easier to read, by escaping the end-of-line character, for example:
$taskAction = New-ScheduledTaskAction -Execute pwsh.exe `
-Argument 'Write-Host "hello world"'
$taskTrigger = New-ScheduledTaskTrigger -Daily `
-At '00:00:00'
Register-ScheduledTask -TaskName 'TaskName' `
-Action $taskAction `
-Trigger $taskTrigger `
-RunLevel 'Limited' `
-Description 'This line is too long to read'
The approach that's used here is relatively common, but it is fragile. It is easy to miss a tick from the end-of-line, or to accidentally add a space after a tick character. Both will break continuation, and the command will still execute but with an incomplete set of parameters; afterwards, an error may be displayed, or a prompt may be shown, depending on the parameter (or parameters) it missed.
This problem is shown in the following screenshot, where a space character has been accidentally included after the Daily switch parameter:
Splatting provides a neater, generally easier to read and more robust alternative. The following example shows one possible way to tackle these commands when using splatting:
$newTaskAction = @{
Execute = 'pwsh.exe'
Argument = 'Write-Host "hello world"'
}
$newTaskTrigger = @{
Daily = $true
At = '00:00:00'
}
$registerTask = @{
TaskName = 'TaskName'
Action = New-ScheduledTaskAction @newTaskAction
Trigger = New-ScheduledTaskTrigger @newTaskTrigger
RunLevel = 'Limited'
Description = 'Splatting is easy to read'
}
Register-ScheduledTask @registerTask
Switch parameters may be treated as if they are Boolean when splatting.
The Daily parameter that was defined in the previous example is a switch parameter.
The same approach will apply to Confirm, Force, WhatIf, Verbose, and so on.