考虑以下函数
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中做到这一点?
3条答案
按热度按时间fquxozlt1#
尝试在您调用的函数和
IfFunctionExistsExecute
函数上创建一个可选参数;就像这样:对我来说,这给了:
kgsdhlau2#
也许你也应该给被调用的函数传递参数:
tf7tbtn23#
我写了我的解决方案。Powershell的样式命名的函数:* 动词-名词 *。它支持命名参数和剩余参数。
使用示例: