I don't see it mentioned here, but splatting your arguments is a useful alternative and becomes especially useful if you are building out the arguments to a command dynamically (as opposed to using Invoke-Expression
). You can splat with arrays for positional arguments and hashtables for named arguments. Here are some examples:
Test-Connection www.google.com localhost
$argumentArray = 'www.google.com', 'localhost'
Test-Connection @argumentArray
Note that when splatting, we reference the splatted variable with an
@
instead of a$
. It is the same when using a Hashtable to splat as well.
Test-Connection -ComputerName www.google.com -Source localhost
$argumentHash = @{
ComputerName = 'www.google.com'
Source = 'localhost'
}
Test-Connection @argumentHash
Test-Connection www.google.com localhost -Count 1
$argumentHash = @{
Count = 1
}
$argumentArray = 'www.google.com', 'localhost'
Test-Connection @argumentHash @argumentArray