【问题标题】:Why does this PowerShell script fail to execute this external command properly?为什么此 PowerShell 脚本无法正确执行此外部命令?
【发布时间】:2011-09-05 08:42:54
【问题描述】:

以下代码将输出我希望运行的命令字符串:

[string] $SourceRepo="C:\inetpub\wwwroot\Spyda\"
[string] $Repo="C:\inetpub\wwwroot\BranchClone\"
[string] $revstring="--rev `"default`" --rev `"case 1234`""

Write-Output "hg clone $SourceRepo $Repo $revstring"

这给了

hg clone C:\inetpub\wwwroot\Spyda\ C:\inetpub\wwwroot\BranchClone\ --rev "default" --rev "case 1234"

如果我从 powershell 提示符运行它,它可以工作,如果我尝试使用这种语法从脚本运行 hg clone 命令,它会失败:

hg clone $SourceRepo $Repo $revstring

给出的错误:

hg.exe : hg clone: option --rev default --rev case not recognized
At line:6 char:3
+ hg <<<<  clone $SourceRepo $Repo $revstring
    + CategoryInfo          : NotSpecified: (hg clone: optio... not recognized:String) [], RemoteE 
   xception
    + FullyQualifiedErrorId : NativeCommandError

【问题讨论】:

    标签: powershell powershell-2.0


    【解决方案1】:

    尝试调用表达式

    $SourceRepo="C:\inetpub\wwwroot\Spyda\"
    $Repo="C:\inetpub\wwwroot\BranchClone\"
    $revstring="--rev `"default`" --rev `"case 1234`""
    
    $cmdString = "hg clone $SourceRepo $Repo $revstring"
    
    Invoke-Expression $cmdString
    

    【讨论】:

      【解决方案2】:

      以这种方式使用调用运算符 (&):

       & '.\hg' clone $SourceRepo $Repo $revstring
      

      【讨论】:

        【解决方案3】:

        使用来自PowerShell Community Extensions 的 EchoArgs.exe,我们可以看到 hg.exe 正在接收哪些参数:

        PS> & ./EchoArgs.exe clone $SourceRepo $Repo $revstring
        Arg 0 is <clone>
        Arg 1 is <C:\inetpub\wwwroot\Spyda\>
        Arg 2 is <C:\inetpub\wwwroot\BranchClone\>
        Arg 3 is <--rev default --rev case>
        Arg 4 is <1234>
        

        powershell 会解析对本机应用程序的调用,因此它会自动使用引号来转义包含空格的变量参数,例如 $revstring

        我们可以通过简单地构建一个我们想要使用的不同值的数组来利用这种转义,而不是预先引用我们的参数:

        PS> $hgArgs = @('clone',$SourceRepo,$Repo,'--rev','default','--rev','case 1234')
        PS> & ./EchoArgs.exe $hgArgs
        Arg 0 is <clone>
        Arg 1 is <C:\inetpub\wwwroot\Spyda\>
        Arg 2 is <C:\inetpub\wwwroot\BranchClone\>
        Arg 3 is <--rev>
        Arg 4 is <default>
        Arg 5 is <--rev>
        Arg 6 is <case 1234>
        

        【讨论】:

          猜你喜欢
          • 2020-06-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多