首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何正确转义命令行参数中的空格和反斜杠?

如何正确转义命令行参数中的空格和反斜杠?
EN

Stack Overflow用户
提问于 2016-03-02 14:55:11
回答 1查看 1.3K关注 0票数 2

我在PowerShell中将字符串数组传递给一个命令时遇到了一些问题,所以我正在调试脚本。我正在使用在EchoArgs.exe中找到的PowerShell社区扩展项目程序。如果我执行这个脚本:

代码语言:javascript
复制
Import-Module Pscx
cls

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

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


EchoArgs $args

我得到了这个结果:

代码语言:javascript
复制
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

如果字符串包含空格,则最后一个反斜杠将转义双引号。事实上,如果我只逃过那个反斜杠,一切似乎都在起作用:

代码语言:javascript
复制
Import-Module Pscx
cls

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

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


EchoArgs $args

有了这个结果:

代码语言:javascript
复制
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)中是否有一种“智能”方法来转义任何字符串以避免此类问题?

EN

回答 1

Stack Overflow用户

发布于 2016-03-05 16:55:45

尝试使用Start-Process代替。它有一个更适合这种情况的$Arguments参数。

见此处:PowerShell -启动进程和Cmdline交换机

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35750665

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档