考虑以下函数
Function IfFunctionExistsExecute
{
param ([parameter(Mandatory=$true)][string]$func)
begin
{
# ...
}
process
{
if(Get-Command $func -ea SilentlyContinue)
{
& $func # the amperersand invokes the function instead of just printing the variable
}
else
{
# ignore
}
}
end
{
# ...
}
}
用法:
Function Foo { "In Foo" }
IfFunctionExistsExecute Foo
这行得通。
然而这不起作用:
Function Foo($someParam)
{
"In Foo"
$someParam
}
IfFunctionExistsExecute Foo "beer"
然而,这给了我一个丑陋的错误:
IfFunctionExistsExecute : A positional parameter cannot be found that accepts argument 'beer'.
At C:\PSTests\Test.ps1:11 char:24
+ IfFunctionExistsExecute <<<< Foo "beer"
+ CategoryInfo : InvalidArgument: (:) [IfFunctionExistsExecute], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,IfFunctionExistsExecute
我如何在 PS 中做到这一点?