考虑一下:
Function Foo
{
param(
#????
)
}
我想这样调用 Foo:
Foo -Bar "test"
没有它爆炸,我没有指定 $bar 参数。那可能吗? :)
更新:
我希望这个工作:
Function IfFunctionExistsExecute
{
param ([parameter(Mandatory=$true)][string]$func, [parameter(Mandatory=$false)][string]$args)
begin
{
# ...
}
process
{
if(Get-Command $func -ea SilentlyContinue)
{
& $func $args # the amperersand invokes the function instead of just printing the variable
}
else
{
# ignore
}
}
end
{
# ...
}
}
Function Foo
{
param([string]$anotherParam)
process
{
$anotherParam
}
}
IfFunctionExistsExecute Foo -Test "bar"
这给了我:
IfFunctionExistsExecute : A parameter cannot be found that matches parameter name 'Test'.
At C:\PSTests\Test.ps1:35 char:34
+ IfFunctionExistsExecute Foo -Test <<<< "bar"
+ CategoryInfo : InvalidArgument: (:) [IfFunctionExistsExecute], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,IfFunctionExistsExecute
最佳答案
我建议两种选择。
首先:您可能需要考虑将整个函数+它的参数作为 scriptblock 参数传递给 ifFunction...
或:使用 ValueFromRemainingArguments:
function Test-SelfBound {
param (
[Parameter(
Mandatory = $true,
HelpMessage = 'Help!'
)]
[string]$First,
[Parameter(
ValueFromRemainingArguments = $true
)]
[Object[]]$MyArgs
)
$Arguments = foreach ($Argument in $MyArgs) {
if ($Argument -match '^-([a-z]+)$') {
$Name = $Matches[1]
$foreach.MoveNext() | Out-Null
$Value = $foreach.Current
New-Variable -Name $Name -Value $Value
$PSBoundParameters.Add($Name,$Value) | Out-Null
} else {
$Argument
}
}
$PSBoundParameters | Out-Default
"Positional"
$Arguments
}
Test-SelfBound -First Test -Next Foo -Last Bar Alfa Beta Gamma
在本例中,我使用 $MyArgs 来存储除了强制参数“First”之外的所有内容。比一些简单的 if 会告诉我它是命名参数(-Next、-Last)还是位置参数(Alfa、Beta、Gamma)。这样,您既可以享受高级函数绑定(bind)(整个 [Parameter()] 装饰)的优点,又可以为 $args 样式的参数留出空间。
关于function - powershell 有没有办法捕获所有命名参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11362785/