PowerShell's argument splatting (see Get-Help about_Splatting
) offers two fundamental choices:
- splatting via a hashtable: works for named arguments only (e.g.,
-Path C:Windows
- splatting via an array-like value: works for positional arguments only (e.g.,
C:Windows
) - except in non-advanced functions that pass all [unbound] arguments through to another command via @args
(i.e., by splatting the automatic $args
array variable containing all unbound arguments), in which case named arguments are also supported, owing to magic built into @args
only.
Note: This dichotomy applies when passing arguments to PowerShell cmdlets / functions (with declared parameters), whereas external programs perform their own argument parsing, which may or may not interpret the set of arguments passed as named.[1]
That said, you can combine either form with regular, individual argument passing - using any combination of individual positional arguments, individual named arguments, hashtable-splatting, and array-splatting.
In both cases, the source data structure must be:
Note: A future enhancement, detailed in this RFC, may bring the ability to splat expressions directly, without the need for an intermediate variable, though as of PowerShell Core 7 it is unclear when this will be implemented.
Examples:
# Positional binding via *array*.
# Note that a function's / script block's parameters are by default positional.
PS> $posArgs = 'one', 'two'; & { param($foo, $bar) "`$foo: $foo"; "`$bar: $bar" } @posArgs
$foo: one
$bar: two
# Named binding via *hashtable*
PS> $namedArgs=@{bar='two';foo='one'}; & { param($foo, $bar) "`$foo: $foo"; "`$bar: $bar" } @namedArgs
$foo: one
$bar: two
# *Combining* hashtable splatting with a regular, positional argument
PS> $namedArgs=@{bar='two'}; & { param($foo, $bar) "`$foo: $foo"; "`$bar: $bar" } @namedArgs one
$foo: one
$bar: two
[1] Splatting with external programs:
Generally, you do not need splatting when you call external programs, because:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…