【问题标题】:How to correctly escape spaces and backslashes in command line arguments?如何正确转义命令行参数中的空格和反斜杠?
【发布时间】:2016-06-15 12:13:19
【问题描述】:

我在将字符串数组传递给 PowerShell 中的命令时遇到了一些问题,因此我正在调试我的脚本。我正在使用PowerShell Community Extension Project (PSCX) 中的EchoArgs.exe 程序。 如果我执行这个脚本:

Import-Module Pscx
cls

$thisOne = 'this_one\';
$secondOne = 'second one\';
$lastOne = 'last_one'

$args = $thisOne `
    , "the $secondOne" `
    , "the_$lastOne"


EchoArgs $args

我得到这个结果:

Arg 0 is <this_one\>
Arg 1 is <the second one" the_last_one>

Command line:
"C:\Program Files (x86)\PowerShell Community Extensions\Pscx3\Pscx\Apps\EchoArgs.exe"  this_one\ "the second one\" the_last_one

似乎如果字符串包含空格,则最后一个反斜杠会转义双引号。事实上,如果我只转义那个反斜杠,一切似乎都正常:

Import-Module Pscx
cls

$thisOne = 'this_one\';
$secondOne = 'second one\\';
$lastOne = 'last_one'

$args = $thisOne `
    , "the $secondOne" `
    , "the_$lastOne"


EchoArgs $args

结果如下:

Arg 0 is <this_one\>
Arg 1 is <the second one\>
Arg 2 is <the_last_one>

Command line:
"C:\Program Files (x86)\PowerShell Community Extensions\Pscx3\Pscx\Apps\EchoArgs.exe"  this_one\ "the second one\\" the_last_one

PowerShell 中是否有“智能”方式(即 cmdlet)来转义任何字符串以避免此类问题?

【问题讨论】:

  • 在你的 PS 脚本中使用单引号怎么样?所以$args = 'this_one', '"the second one"', 'the_last_one'
  • 你是对的,但我必须在我的数组字符串中使用变量,如$args = "$thisOne" 等等。
  • 我刚刚更新了代码 sn-ps。谢谢
  • 旁注:不要使用$args,它是一个自动变量

标签: powershell command-line arguments escaping


【解决方案1】:

尝试改用Start-Process。它有一个$Arguments 参数更适合这个。

请看这里:PowerShell - Start-Process and Cmdline Switches

【讨论】:

    猜你喜欢
    • 2012-03-06
    • 2017-03-03
    • 2021-11-02
    • 2012-02-25
    • 1970-01-01
    • 2020-03-21
    • 2011-01-28
    • 1970-01-01
    • 2019-12-12
    相关资源
    最近更新 更多