这些示例适用于函数(简单和高级),但同样的想法也适用于脚本param
:
# Simple function.
# Everything not declared in `param` goes to $args.
# If $args is not empty then there are "invalid" parameters or "unexpected" arguments
function test {
param (
[string]$path,
[int]$days,
[int]$hours
)
# check $args and throw an error (in here we just write a warning)
if ($args) { Write-Warning "Unknown arguments: $args" }
}
或者
# Advanced function.
# For an advanced function we can use an extra argument $args
# with an attribute `[Parameter(ValueFromRemainingArguments=$true)]`
function test {
param (
[Parameter(Mandatory=$true )] [string] $path,
[Parameter(Mandatory=$false)] [int] $days,
[Parameter(Mandatory=$false)] [int] $hours,
[Parameter(ValueFromRemainingArguments=$true)] $args
)
# check $args and throw an error (in this test we just write a warning)
if ($args) { Write-Warning "Unknown arguments: $args" }
}
以下测试:
# invalid parameter
test -path p -invalid -days 5
# too many arguments
test -path p 5 5 extra
在这两种情况下都会产生相同的输出:
WARNING: Unknown arguments: -invalid
WARNING: Unknown arguments: extra