tl;dr
您的整个"..."-enclosed JSON 字符串已嵌入 ",必须将其转义为\"(原文如此;命令简化):
powershell.exe -File "C:\...\customscript.PS1" ... -jsonContent "{ \"c\": \"some setting\", \"d\": \"unknown\", \"b\": \"some thing\", \"a\": 1 }"
请继续阅读,了解何时需要额外转义、-File 调用与 -Command 调用有何不同,以及调用 shell(您从哪里调用 powershell.exe)的重要性。
注意:
PowerShell CLI 所需的语法 - 即使用参数调用powershell.exe - 取决于:
无论哪种方式,您最初的尝试都无法奏效,因为 包含空格,无法将文字 { "c": "some setting" ... } 识别为单个参数 strong> 并且 整体上没有用引号括起来;稍后添加的命令,包含 "...",缺少对嵌入的 " 的转义。
以下命令使用简化的 JSON 字符串演示了所讨论场景所需的语法。
要使-File 命令可运行,请在当前目录中创建script.ps1 文件。内容如下:ConvertFrom-Json $Args[0]
从cmd.exe/批处理文件调用
-
嵌入的" 必须转义为\"(即使PowerShell-在内部你会使用`")。
-
重要:
-
如果 JSON 文本包含
cmd.exe元字符(总是在 \"...\" 运行之间),您必须^-单独转义它们,因为cmd.exe,由于没有将\" 识别为转义的",因此将这些子字符串视为未引用;例如,\"some & setting\" 必须转义为 \"some ^& setting\";这里需要转义的cmd.exe 元字符是:
& | < > ^
-
cmd.exe-style 环境变量引用,例如 %USERNAME% 是插值 - cmd.exe 没有文字 字符串语法,它只识别"...",插值会发生,就像在未引用标记中一样。
如果您想按原样传递这样的标记,即 suppress 插值,转义语法取决于您是从 命令行 还是从 批处理文件,遗憾的是:使用前者的%^USERNAME%,使用后者的%%USERNAME%% - 有关血腥细节,请参见this answer。
-
注意-Command 调用如何通过将"..." 字符串包含在'...' 中来简单地添加另一层引用。这是必需的,因为-Command PowerShell 将其接收到的参数视为 PowerShell 源代码 而不是 文字参数(后者是 -File 的情况);如果不是封闭的'...',整个封闭的"..." 将在解释之前剥离。
-File:
# With a literal string:
powershell -File ./script.ps1 "{ \"c\": \"some setting\", \"unknown\": \"b\" }"
# With an expandable string (expanded by the caller):
powershell -File ./script.ps1 "{ \"c\": \"some %USERNAME%\", \"unknown\": \"b\" }"
-Command:
# With a literal string:
powershell -Command ConvertFrom-Json '"{ \"c\": \"some setting\", \"unknown\": \"b\" }"'
# With an expandable string (expanded by the caller):
powershell -Command ConvertFrom-Json '"{ \"c\": \"some %USERNAME%\", \"unknown\": \"b\" }"'
从 PowerShell 本身调用
使用-File 或调用外部程序,例如curl.exe:
# With a literal string:
powershell -File ./script.ps1 '{ \"c\": \"some setting\", \"unknown\": \"b\" }'
# With an expandable string (expanded by the caller):
powershell -File ./script.ps1 "{ \`"c\`": \`"some $env:OS\`", \`"unknown\`": \`"b\`" }"
与-Command:
# With a literal string:
powershell -Command ConvertFrom-Json '''"{ \"c\": \"some setting\", \"unknown\": \"b\" }"'''
# With an expandable string (expanded by the caller):
powershell -Command ConvertFrom-Json "'{ \`"c\`": \`"some $env:OS\`", \`"unknown\`": \`"b\`" }'"
PowerShell Core:从bash调用
-File:
# With a literal string:
pwsh -File ./script.ps1 '{ "c": "some setting", "unknown": "b" }'
# With an expandable string (expanded by the caller):
pwsh -File ./script.ps1 "{ \"c\": \"some $USER\", \"unknown\": \"b\" }"
-Command:
# With a literal string:
pwsh -Command ConvertFrom-Json \''{ "c": "some setting", "unknown": "b" }'\'
# With an expandable string (expanded by the caller):
pwsh -Command ConvertFrom-Json "'{ \"c\": \"some $USER\", \"unknown\": \"b\" }'"