例は関数 (単純および高度) 用ですが、同じ考え方が次のスクリプトで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