为什么参数 $args after = sign 没有得到扩展? ($args 作为 jvm 典型 -D 开关的参数)

Why does an argument $args after = sign not get expanded? ($args as parameter to jvm typical -D switch)

我的 *profile.ps1 文件中有以下定义:

if(Test-Path $env:M2_HOME){
    function mvn{
            $cmd = "$env:M2_HOME\bin\mvn.bat"
            & $cmd $args
    }
}

当我在 powershell 中使用此函数定义函数时,例如:

function d { mvn help:describe $args }

使用类似:

d -Dplugin=jar

一切都很好,而不是将后者定义为:

function d { mvn help:describe -Dplugin=$args }

使用类似:

d jar

是否有一些内置函数可以处理这种特殊情况?

通过调用函数获取参数你应该像这样使用

function test {
write-host $args[0]
write-host $args[1]
}

test Whosebug powershell

产出

Whosebug
powershell

Whosebugfirst argument 传递给函数,powershellsecond argument 传递给函数 对于传递给函数的每个参数

function test {
foreach ($a in $args){
write-host "output:$args"
}
}

测试 1 2 3 4 5 6 7 8

输出:

test 1 2 3 4 5 6 7 8 
output:1 2 3 4 5 6 7 8
output:1 2 3 4 5 6 7 8
output:1 2 3 4 5 6 7 8
output:1 2 3 4 5 6 7 8
output:1 2 3 4 5 6 7 8
output:1 2 3 4 5 6 7 8
output:1 2 3 4 5 6 7 8
output:1 2 3 4 5 6 7 8

你的功能

 if(Test-Path $env:M2_HOME){
        function mvn{
                $cmd = "$env:M2_HOME\bin\mvn.bat"
foreach ($arg in $args) {

                & $cmd $args}
        }
    }

好像有人做了a similar observation: 原因似乎 -D 是 powershell 中的一个特殊字符,或多或少地标记了由 -D 确定的每个特定特殊选项字符串的确切结束位置,至少对我的调用函数的这种修改对我有用:

function x {mvn help:describe `-Dplugin=$args}

当然,以某种方式在托管功能中处理此类情况会很好(mvn 我的 *profile.ps1 中的定义),但该解决方案似乎超出了我的问题范围。

看来您只需要确保将参数作为字符串传递并确保首先对它们进行求值:

function mvn{
  $cmd = "$env:M2_HOME\bin\mvn.bat"
  & $cmd $args
}

function d { mvn "help:describe" "-Dplugin=$($args)" }