PowerShell JSON 字符串转义(反斜杠)

Chr*_*utt 3 powershell json

我需要使用 PowerShell 脚本将 Json 主体 HttpPost 发送到 ASP.NET Core Web Api 端点(控制器)。

$CurrentWindowsIdentity = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$CurrentPrincipalName = $CurrentWindowsIdentity.Identity.Name

# Build JSON payload
$JsonString = @"
{
    "CurrentPrincipalName":"$CurrentPrincipalName"
}
"@

$response = Invoke-RestMethod -Uri "https://webapiendpoint.tld/api/somecontroller" -Method Post -Body $JsonString -ContentType "application/json"
Run Code Online (Sandbox Code Playgroud)

由于变量 $CurrentPrincipalName 的值可以是域\用户名,由于反斜杠未正确转义,json get 无效。

web api 的日志中的错误:

  JSON input formatter threw an exception: 'C' is an invalid escapable character within a JSON string. The string should be correctly escaped. Path: $.CurrentPrincipalName | LineNumber: 15 | BytePositionInLine: 36.
  System.Text.Json.JsonException: 'C' is an invalid escapable character within a JSON string. The string should be correctly escaped. Path: $.CurrentPrincipalName
Run Code Online (Sandbox Code Playgroud)

我如何确保在创建 json 字符串和添加变量时 - 当然无法控制其值 - json 字符串得到正确转义?

我也试过 ConvertTo-Json,比如:

$JsonConverted = $JsonString | ConvertTo-Json
Run Code Online (Sandbox Code Playgroud)

然后 HttpPost 那个对象,但那更糟:

JSON input formatter threw an exception: The JSON value could not be converted to solutionname.model. Path: $ | LineNumber: 0 | BytePositionInLine: 758.
Run Code Online (Sandbox Code Playgroud)

mkl*_*nt0 6

创建 JSON 文本的可靠方法是首先将数据构造为哈希表 ( @{ ... }) 或自定义对象 ( [pscustomobject] @{ ... }),然后通过管道传输到ConvertTo-Json

$JsonString = @{
  CurrentPrincipalName = $CurrentPrincipalName
} | ConvertTo-Json
Run Code Online (Sandbox Code Playgroud)

这样,PowerShell 会为您执行任何必要的值转义,特别是包括将值中的文字\字符加倍$CurrentPrincipalName以确保将其视为文字.

笔记:

  • 根据如何深度嵌套的哈希表是,你可能有一个添加-Depth参数ConvertTo-Json调用,以防止越来越多截断数据-看到这个帖子以获取更多信息。

  • 如果您有多个属性并希望在 JSON 表示中保留它们的定义顺序,请使用有序哈希表 ( [ordered] @{ ... }) 或自定义对象。