【问题标题】:Stop powershell from putting doublequotes around arguments阻止 powershell 在参数周围加上双引号
【发布时间】:2016-09-08 12:01:27
【问题描述】:

我想像这样执行一个外部程序

& $exe $arguments

$arguments 是带空格的字符串,可以说是a b c d

发生的情况是传递给 exe 的参数是 "a b c d"

用双引号括住整个内容。 $arguments 不包含空格时不会发生这种情况。

如何防止 powershell 试图变得聪明并阻止它用双引号将我的字符串包裹起来?假设所有带空格的东西都必须是路径,这是荒谬的。

编辑:由于显然不存在修复程序,因此我确实通过将每一位转换为数组来解决问题,并且它在 PS 5 中确实有效。但是 PS4 正在 ****...

我想要的是有一个命令行参数,看起来像 -filter:"+[RE*]* +[RR*]*"

PS 4 也将双引号括起来: $filter = "+[RE*]*", "+[RR*]*" & $opencover -target:"$xunit" "-targetargs:$allPaths $traitsCmd -quiet -nunit xunit-$results -noshadow" -register:user -filter:"$filter" -output:opencover-$results

如果我将 -filter: 替换为 '-filter:' 我最终会在 -filter: 和 $filter 数组的内容之间出现一个空格。无论我做什么,我都无法摆脱它,除非将整个内容用双引号括起来,例如“-filter:...”

【问题讨论】:

  • 您是否尝试过用单引号声明$arguments,例如:$arguments = 'a', 'b', 'c', 'd'?如果不试试这个
  • a b c d 可以说明问题。在我的脚本中,这些要复杂得多,并且是以编程方式创建的
  • 它没有,因为我没有字符串文字。我有表达式,它们不会在单引号内展开
  • 谢谢我试试
  • 在 PS4 中不起作用。它确实可以单独工作,但如果整个事情是一个参数,PS4 会将它用双引号括起来

标签: powershell


【解决方案1】:

你应该做一个数组而不是尝试。 所以在你的情况下:

$exe = "ping.exe"
$arguments = "-t","8.8.8.8"
& $exe $arguments

请注意$args 是一个特殊值,不能分配给任何东西。这就是我在示例中使用$arguments 的原因。

你的问题的答案是这样的:

$arguments = "a","b","c","d"
& $exe $arguments

【讨论】:

  • 我有那个。问题是,即使数组元素包含空格。 powershell 将其用双引号括起来。我只需要阻止 powershell 变得伪智能。
【解决方案2】:

我强烈建议使用 Start-Process 而不是使用 .& 调用运算符,以便从 PowerShell 调用外部可执行文件。

Start-Process 命令更容易预测,因为您分别输入可执行文件和命令行参数的路径。这种方式没有任何特殊的解释(又名“魔法”)。

$MyProcess = Start-Process -FilePath $exe -ArgumentList $arguments -Wait

我在其他几个 StackOverflow 线程上分享了类似的建议。

Powershell "Start-process" not running as scheduled task

Accessing output from Start-Process with -Credential parameter

【讨论】:

  • 一旦您了解了基本规则,“魔术”就非常简单。此外,我还编写了 showargs.exe 实用程序来准确地向您展示 PowerShell 正在做什么(不再有解析之谜)。这一切都在an article 中有所描述,我之前写过。
【解决方案3】:

将空格分隔的字符串拆分成一个数组:

$arguments = "a b c d"
$arguments = $arguments -split '\.'
& $exe $arguments

【讨论】:

    【解决方案4】:

    将复杂参数传递给 exe 时,请考虑使用停止解析运算符:--%。从该运算符到行尾,PowerShell 解析“功能”消失了,文本的解析与 CMD 解析文本的方式非常相似。其实引用变量的唯一方式就是CMD方式%var% e.g:

    77> $env:arguments = 'a b c d'
    78> echoargs --% %arguments%
    Arg 0 is <a>
    Arg 1 is <b>
    Arg 2 is <c>
    Arg 3 is <d>
    
    Command line:
    "C:\Users\Keith\Documents\WindowsPowerShell\Modules\Pscx\3.2.2\Apps\EchoArgs.exe"  a b c d
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-21
      相关资源
      最近更新 更多