简体   繁体   English

PowerShell:在传递给外部程序的字符串中转义双引号的最佳方法? 例如,一个 JSON 字符串

[英]PowerShell: best way to escape double quotes in string passed to an external program? E.g., a JSON string

I read I think all the articles on escaping strings in PowerShell, but I still haven't found the solution that would satisfy me.我阅读了所有关于在 PowerShell 中转义字符串的文章,但我仍然没有找到让我满意的解决方案。

Suppose I have a file foo.json that contains a JSON string.假设我有一个包含 JSON 字符串的文件foo.json I need to pass the JSON string to a program as an argument.我需要将 JSON 字符串作为参数传递给程序。

In bash, this works just fine:在 bash 中,这工作得很好:

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

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.在 PowerShell 中,当我正常读取文件内容并将其传入时,接收程序会抱怨键和值周围没有引号。

What I've come up with is:我想出的是:

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

Is there a less awkward way to do this in PowerShell?在 PowerShell 中有没有更尴尬的方法来做到这一点? I've resorted to exiting the session, running the command in bash, then starting the session again.我已经退出会话,在 bash 中运行命令,然后再次启动会话。

Unfortunately, PowerShell's passing of arguments with embedded double quotes to external programs is broken up to at least PowerShell 7.2 , requiring you to manually \ -escape them as \" :不幸的是, PowerShell 将带有嵌入式双引号的参数传递给外部程序至少被分解为PowerShell 7.2 ,需要您手动将它们\\"

  • See this answer for more information about the underlying problem.有关潜在问题的更多信息,请参阅此答案

A robust workaround requires not only replacing all " with \" , but also doubling any \ immediately preceding them.一个强大的解决方法不仅需要将所有"替换为\" ,而且还需要将它们之前的任何\加倍。

# Note: If your JSON has no embedded *escaped* double quotes
#       - \" - you can get away with: -replace '"', '\"'
myprogram ((Get-Content -Raw ~/foo.json) -replace '([\\]*)"', '$1$1\"')

Note the use of Get-Content -Raw , which is preferable to Get-Content ... | Out-String注意Get-Content -Raw的使用,它优于Get-Content ... | Out-String Get-Content ... | Out-String for reading the entire file into a single , multi-line string, but note that it requires PSv3+. Get-Content ... | Out-String用于将整个文件读入单个多行字符串,但请注意它需要 PSv3+。


Assuming that your JSON contains either no escape sequences at all or only instances of \" , a simpler workaround, discovered by Vivere , is to encode the JSON strings as JSON again , via ConvertTo-Json :假设您的 JSON 根本不包含转义序列或仅包含\"的实例, Vivere发现的一个更简单的解决方法是通过ConvertTo-Json将 JSON 字符串再次编码为 JSON:

# Works, but only if your JSON contains no escape sequences
# such as \n or \\
myprogram (Get-Content -Raw ~/foo.json | ConvertTo-Json)

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

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