繁体   English   中英

从批处理脚本中调用Powershell命令时,双引号是否不能从字符串转义?

[英]Double quotes not escaping from string when calling Powershell command from within Batch script?

通过批处理脚本调用的Powershell实例传递时,双引号结构未保留在测试消息中,如下所示:

set test={"this":"is","a":"test"}
FOR /F "delims=" %%i in (' powershell -Command "& {$message = '%test%'; echo $message}" ') DO SET message=%%i
echo %test%
echo %message%

输出如下:

{"this":"is","a":"test"}
{this:is,a:test}

我想保留引号以进一步在powershell中处理字符串,但是如您所见,将引号引入$message变量后会删除它们。

关于如何解决此问题的任何见解?

在d-引用的powershell命令中回显包含双引号的%test%会破坏包围的d-引号。

解决此问题的一种方法是使用批处理字符串替换以动态反斜线转义内部d引号

:: Q:\Test\2019\04\25\SO_55855412.cmd
@Echo off
set "test={"this":"is","a":"test"}"
FOR /F "delims=" %%i in ('
     powershell -Command "& {$message = '%test:"=\"%'; echo $message}" 
') DO SET "message=%%i"
echo %test%
echo %message%

返回此处:

> SO_55855412.cmd
{"this":"is","a":"test"}
{"this":"is","a":"test"}

另一个解决方案是通过%test%作为参数,而是从继承的环境中获取变量。

    powershell -Command "& {$message = $env:test; echo $message}"

遗憾的是,这无法将变量传递回来,因为在终止生成的应用程序时,继承的环境将被丢弃。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM