如何在Powershell中使用破折号参数?

时间:2019-06-25 09:27:31

标签: powershell parameter-passing

我正在将脚本从bash移植到PowerShell,并且我想在两者中保持对参数解析的相同支持。在bash中,可能的参数之一是--,我也想在PowerShell中检测该参数。但是,到目前为止,我没有尝试过任何方法。我无法将其定义为param($-)之类的参数,因为这会导致编译错误。另外,如果我决定完全放弃PowerShell参数的处理,而只使用$args,一切似乎都很好,但是当我运行该函数时,--参数就丢失了。

Function Test-Function {
    Write-Host $args
}

Test-Function -- -args go -here # Prints "-args go -here"

我也了解$PSBoundParameters,但是值不存在,因为我无法绑定名为$-的参数。这里还有其他我可以尝试的机制或任何解决方案吗?

有关更多上下文,请注意,使用PowerShell是一种副作用。不应将其用作常规的PowerShell命令,我也为此编写了一个批处理包装器,但是该包装器的逻辑比我想批量编写的更为复杂,因此该批处理包装器仅调用PowerShell函数,然后进行更复杂的处理。

2 个答案:

答案 0 :(得分:3)

我找到了一种方法,但是您不必传递双连字符,而必须传递其中的3个。

这是一个简单的功能,您可以根据需要更改代码:

function Test-Hyphen {
    param(
        ${-}
    )
    if (${-}) {
        write-host "You used triple-hyphen"
    } else {
        write-host "You didn't use triple-hyphen"
    }
}

示例1

Test-Hyphen

输出

You didn't use triple-hyphen

示例2

Test-Hyphen ---

输出

You used triple-hyphen

答案 1 :(得分:1)

顺便说一句:PowerShell允许使用各种变量名,但是必须将它们括在{...}中才能被识别;也就是说,${-}从技术上讲是可行的,但不能解决您的问题。

挑战在于, PowerShell从参数列表中悄悄地 strips -- -并且唯一保留 的方法>该令牌是您在PSv3 + stop-parsing symbol, --% 之前使用的,但是,从根本上改变了参数的传递方式,显然这是一个额外的要求,这就是您要做的重新尝试避免。

您最好的选择是尝试-次优-解决方法

  • 选项A:在批处理文件包装程序中,将--转换为PowerShell 保留的特殊参数,然后将其传递;然后,PowerShell脚本将不得不将该特殊参数重新转换为--

  • 选项B:在PowerShell中执行自定义参数解析:

您可以分析$MyInvocation.Line,其中包含调用脚本的原始命令行,然后在其中查找--的存在。

但是要做到这一点并使其健壮起来并非易事。
这是一种合理可靠的方法:

# Don't use `param()` or `$args` - instead, do your own argument parsing:

# Extract the argument list from the invocation command line.
$argList = ($MyInvocation.Line -replace ('^.*' + [regex]::Escape($MyInvocation.InvocationName)) -split '[;|]')[0].Trim()

# Use Invoke-Expression with a Write-Output call to parse the raw argument list,
# performing evaluation and splitting it into an array:
$customArgs = if ($argList) { @(Invoke-Expression "Write-Output -- $argList") } else { @() }

# Print the resulting arguments array for verification:
$i = 0
$customArgs | % { "Arg #$((++$i)): [$_]" }

注意:

  • 毫无疑问,在某些极端情况下,可能无法正确提取参数列表,或者对原始参数进行重新评估会产生副作用,但在大多数情况下,尤其是从 outside < / em> PowerShell-应该可以。

  • 在此有用,Invoke-Expression should generally be avoided

如果您的脚本名为foo.ps1,并且您以./foo.ps1 -- -args go -here的身份调用了脚本,则会看到以下输出:

Arg #1: [--]
Arg #2: [-args]
Arg #3: [go]
Arg #4: [-here]