windows - 如何在PowerShell一线式中转义空间

标签 windows powershell escaping quoting

我想使用powershell一行运行带有参数的exe,如下所示-

powershell -ExecutionPolicy Unrestricted "Start-Process -Path program.exe -ArgumentList somefile.txt, Run"

它可以正常工作,但是当我尝试插入带有空格的完整路径时,它崩溃了
powershell -ExecutionPolicy Unrestricted "Start-Process -Path program.exe -ArgumentList "C:\Program Files\somefile.txt", "Run" "

我试图使用单引号或将其与`转义,但这无济于事

也许有人知道我做错了吗?

P.s.从cmd.exe内部运行

最佳答案

最简单的解决方案是对嵌入的字符串使用单引号('...'):

powershell -ExecutionPolicy Unrestricted "Start-Process -Path program.exe -ArgumentList 'C:\Program Files\somefile.txt', 'Run'"

由于是PowerShell将解释命令字符串,因此它将嵌入式'...'字符串识别为字符串文字。

如果您尝试嵌入双引号字符串("..."),则面临两个障碍:
  • 首先,PowerShell的CLI要求\作为"的转义字符(而内部是`),因此您需要将整个"命令字符串中的"..."转义为\"
  • 此外,由于使用了known problem with Start-Process ,因此需要进行额外的转义,这使解决方案变得晦涩难懂,因为必须将每个嵌入的"都转义为\"`\" (!)。

  • powershell -ExecutionPolicy Unrestricted "Start-Process -Path program.exe -ArgumentList \"`\"C:\Program Files\somefile.txt\"`\", \"`\"Run\"`\" "
    

    关于windows - 如何在PowerShell一线式中转义空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51596550/

    相关文章:

    regex - 如何在 Apache `/` 指令的正则表达式中转义斜杠符号 `<If>`?

    json - Delphi 解码 json/utf8 转义文本

    DLL 源代码中的 C++ 函数 Hook

    c# - Hook 哪些用户模式函数来监视/拦截文件访问?

    windows - Windows 10 中的主文件夹是否有别名?

    .net - 写入远程 MSMQ

    powershell - 如何从.ps1文件运行powershell脚本?

    regex - 正则表达式用于匹配特定单词并忽略换行

    powershell - 在文件中的引号之间替换字符串内容

    postgresql - 如何在不将其保存为 "\%"的情况下使用 PostgreSQL 中的文字百分比文字 (%) 更新记录