PowerShell中的函数指针

o2rvlv0m  于 2023-04-30  发布在  Shell
关注(0)|答案(3)|浏览(110)

考虑以下函数

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

fquxozlt

fquxozlt1#

尝试在您调用的函数和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>
kgsdhlau

kgsdhlau2#

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

$arguments = $args[1..($args.Length-1)]
& $func @arguments
tf7tbtn2

tf7tbtn23#

我写了我的解决方案。Powershell的样式命名的函数:* 动词-名词 *。它支持命名参数和剩余参数。

function Invoke-FunctionIfExist {
    [CmdletBinding()]
    param (
        # Function name
        [Parameter(Mandatory, Position=0)]
        [string]
        $Name,
        # Hashtable with named arguments
        [Parameter()]
        [hashtable]
        $Parameters = @{},
        # Rest of arguments
        [Parameter(ValueFromRemainingArguments)]
        [object[]]
        $Arguments = @()
    )

    process {
        if (Get-Command $Name -ErrorAction SilentlyContinue) {
            & $Name @NamedArguments @Arguments
        }
    }
}

使用示例:

PS> Invoke-FunctionIfExist Foo
In Foo
PS> Invoke-FunctionIfExist Foo beer
In Foo
beer
PS> Invoke-FunctionIfExist Foo -Parameters @{someParam='beer'}
In Foo
beer

相关问题