function - powershell 有没有办法捕获所有命名参数

标签 function powershell arguments

考虑一下:

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/

相关文章:

powershell - 在 powershell 中并行运行任务

c++ - 以对象为参数的函数,作为另一个函数的参数

python - 使用不同的参数在 python 中调用父类(super class)构造函数

windows - 将 Sitecore PowerShell 扩展与 native PowerShell 结合使用

java - Sams Teach Yourself Java in 24 Hours Rogers Cadenhead MP3 第 20 章 MP3 文件错误第六版

java - 一个 Action 的多个 Java 消费者

python - 从python中的函数返回不同的数据类型

php - 如何将两个四元数相乘

c++ - 我想存储指向函数的空指针及其类型

powershell - 为什么将true分配给变量it不会得出true?