Splatting – a cool use for hashtables
Some PowerShell cmdlets take a lot of parameters, and it can be confusing to feed them all into the cmdlet one at a time, all on the same line. Hashtables to the rescue. Try the following:
$Colors = @{ ForegroundColor = 'red' BackgroundColor = 'white' } Write-Host 'all the pretty colors' @Colors
Notice that we don’t use $Colors
; we use @Colors
. Also, notice it doesn’t matter which way round we use it:
Write-Host @Colors 'OK, just red and white, then'
This will work as well, because we’ve explicitly named the parameters in the hashtable:
Figure 4.25 – A basic example of splatting
We could use an array, but that will only work for positional parameters; the first value in the array will be the first positional parameter, the second value will be the second, and so on. Because most cmdlets don’t have more than one or two positional...