1

考虑以下函数

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 中做到这一点?

4

2 回答 2

1

尝试在您调用的函数和您的函数上创建一个可选参数IfFunctionExistsExecute;像这样的东西:

Function IfFunctionExistsExecute
{
    param ([parameter(Mandatory=$true)][string]$func, [string]$myArgs)
        if(Get-Command $func -ea SilentlyContinue)
        {
            & $func $myArgs  # the amperersand invokes the function instead of just printing the variable
        }
        else
        {
            # ignore
        }       
}

Function Foo
{ 
    param ([parameter(Mandatory=$false)][string]$someParam)
    "In Foo" 
    $someParam
}

IfFunctionExistsExecute Foo
IfFunctionExistsExecute Foo "beer"

对我来说,这给出了:

C:\test>powershell .\test.ps1
In Foo

In Foo
beer

C:\test>
于 2012-07-06T12:11:01.913 回答
0

也许您也应该将参数传递给被调用的函数:

$arguments = $args[1..($args.Length-1)]
& $func @arguments
于 2012-07-06T11:35:27.003 回答