命令行参数中的PowerShell变量插值

时间:2018-09-28 15:19:17

标签: json string powershell escaping interpolation

说明

我在将JSON字符串正确传递到命令时遇到麻烦。我相信我已经重现了我在测试信念中遇到的问题。 JSON字符串使用双引号字符串,并且在字符串主体中也包含双引号。

问题:

当我直接使用参数调用Powershell脚本时,该脚本会正确地回显JSON字符串。当我使用eventReactive调用PowerShell脚本时,JSON字符串似乎被规避或解析,例如删除了双引号(因此使JSON字符串无效)。

示例:

powershell.exe

当我直接调用test.ps1文件时,输出看起来就像我期望的那样:

# Contents test.ps1 file
echo $args[0]
echo $args[1]

# Back to PowerShell
> $a='bar'
> $b="{`"foo`": `"$a`"}"
> $b
{"foo": "bar"} # <-- Looks correct

但是,如果我进一步进行间接访问一级并使用> .\test.ps1 foo $b foo {"foo": "bar"} # <-- Looks correct 来调用该命令,则不会获得预期的结果:

powershell.exe

我正在尝试确定如何获取powershell.exe命令以输出带引号的完整JSON字符串。

1 个答案:

答案 0 :(得分:3)

当您将powershell.exe传递给字符串时,它将作为表达式调用它。

powershell.exe "Get-Date"

这就是PowerShell调用您的字符串的原因。

您可以这样解决问题:

$a='bar'
$b="{`"foo`": `"$a`"}"
powershell.exe -command {.\test.ps1 'foo' $args[0]} -args $b