PowerShell:避免传递给外部程序的字符串中的双引号转义的最佳方法?例如,一个JSON字符串 [英] PowerShell: best way to escape double quotes in string passed to an external program? E.g., a JSON string

查看:113
本文介绍了PowerShell:避免传递给外部程序的字符串中的双引号转义的最佳方法?例如,一个JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过我认为所有有关在PowerShell中转义字符串的文章,但我仍然没有找到让我满意的解决方案.

I read I think all the articles on escaping strings in PowerShell, but I still haven't found the solution that would satisfy me.

假设我有一个包含JSON字符串的文件foo.json.我需要将JSON字符串作为参数传递给程序.

Suppose I have a file foo.json that contains a JSON string. I need to pass the JSON string to a program as an argument.

在bash中,它可以正常工作:

In bash, this works just fine:

myprogram "$(cat ~/foo.json)"

myprogram "$(cat ~/foo.json)"

在PowerShell中,当我正常读取文件的内容并将其传递时,接收程序会抱怨键和值周围没有引号.

In PowerShell, when I read the contents of the file normally and pass it in, the receiving program complains about there not being quotes around the keys and the values.

我想出的是:

$json = (get-content ~/foo.json | Out-String) -replace '"','""' myprogram $json

$json = (get-content ~/foo.json | Out-String) -replace '"','""' myprogram $json

在PowerShell中是否有一种不太麻烦的方法来做到这一点?我不得不退出会话,以bash运行命令,然后再次启动会话.

Is there a less awkward way to do this in PowerShell? I've resorted to exiting the session, running the command in bash, then starting the session again.

推荐答案

不幸的是, PowerShell将带有嵌入式双引号的参数传递给外部程序的操作已损坏,需要您 手动 \-转义\":

Unfortunately, PowerShell's passing of arguments with embedded double quotes to external programs is broken, requiring you to manually \-escape them as \":

myprogram ((Get-Content -Raw ~/foo.json) -replace '"', '\"')

请注意,使用Get-Content -Raw优于Get-Content ... | Out-String,以便将整个文件读取为多行字符串,但请注意,它需要PSv3 +. /sup>

Note the use of Get-Content -Raw, which is preferable to Get-Content ... | Out-String for reading the entire file into a single, multi-line string, but note that it requires PSv3+.

有关更多信息,请参见此答案.

See this answer for more information.

这篇关于PowerShell:避免传递给外部程序的字符串中的双引号转义的最佳方法?例如,一个JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆