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

PowerShell JSON字符串转义(反斜杠),json,powershell,Json,Powershell,我需要使用PowerShell脚本向ASP.NET核心Web Api端点控制器HttpPost一个Json主体 $CurrentWindowsIdentity = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) $CurrentPrincipalName = $CurrentWindowsIdentity.Identity.Name # Buil

我需要使用PowerShell脚本向ASP.NET核心Web Api端点控制器HttpPost一个Json主体

$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"
由于变量$CurrentPrincipalName的值可以是domain\username,因此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
我如何确保在创建json字符串并添加变量(其值当然无法控制)时,json字符串正确转义

我还尝试转换为Json,比如:

$JsonConverted = $JsonString | ConvertTo-Json
然后HttpPost发布了该对象,但更糟糕的是:

JSON input formatter threw an exception: The JSON value could not be converted to solutionname.model. Path: $ | LineNumber: 0 | BytePositionInLine: 758.

创建JSON文本的可靠方法是首先将数据构造为哈希表@{…}或自定义对象[pscustomobject]@{…},然后通过管道发送到:

这样,PowerShell将为您执行任何必要的值转义,特别是将$CurrentPrincipalName值中的literal\字符加倍,以确保它被视为一个literal

注:

根据哈希表的嵌套深度,您可能必须向ConvertTo Json调用添加-Depth参数,以防止更多数据被截断-有关更多信息,请参阅

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


作为一个备用re$JsonString | ConvertTo Json:ConvertTo Json设计用于将哈希表或自定义对象转换为Json;如果您将已经是JSON字符串的内容传递给它,您将得到一个包含在文本双引号中的JSON字符串值,并且输入对象结构将丢失。尝试“{foo:1}”|转换为JsonAgree。好的,部分地,只是碰到了另一个问题:$CurrentPrincipalIsAdmin=$CurrentWindowsIdentity.IsInRole[Security.Principal.WindowsBuiltInRole]::管理员需要是$CurrentPrincipalIsAdmin=$CurrentWindowsIdentity.IsInRole[Security.Principal.WindowsBuiltInRole]::Administrator.ToString否则:这:$JsonString=@{CurrentPrincipalIsAdmin=$CurrentPrincipalIsAdmin}| ConvertTo Json导致System.InvalidOperationException:无法将令牌类型“True”的值作为字符串获取。但这超出了此处的范围,必须创建一个新的问题ithink@ChristianCasutt这是一个奇怪的错误,我不希望-布尔值是绝对支持的。如果你有一个可复制的案例,请发布一个新的问题,提供有关特定PowerShell版本的详细信息。请尝试:ConvertTo Json-Depth 1024
$JsonString = @{
  CurrentPrincipalName = $CurrentPrincipalName
} | ConvertTo-Json