通过批处理脚本调用的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}"
遗憾的是,这无法将变量传递回来,因为在终止生成的应用程序时,继承的环境将被丢弃。
关于powershell - 从批处理脚本中调用Powershell命令时,双引号是否不能从字符串转义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55855412/