PowerShell调用REST API时如何在请求体传入带单引号的值
解决PowerShell请求体中Number字段值带单引号的问题
问题场景
在Azure PowerShell任务中执行以下脚本调用REST API时出现内部服务器错误,需要将请求体的Number字段设置为'12000'(值带单引号)的格式:
$cd = 12000 $Url = 'https://exampleSet/Set' $Body = @{ OperationType = 'new' Number = "'$($cd)'" CdAspId = 'Z_CK_BUGFIX' CdType = 'CA_106_4' } | ConvertTo-Json $headers = @{ 'ContentType' = 'application/json' 'Accept' = 'application/json' 'APIKey' = 'abcdef' } Invoke-RestMethod -contentType "application/json" -Uri $url -Method Post -body $Body -Headers $headers
解决方案
修正请求体写法
原脚本中"是HTML转义的双引号,在PowerShell中无需这样写。要让Number的值包含单引号,直接用双引号包裹字符串即可实现变量展开并保留单引号:
$cd = 12000 $Url = 'https://exampleSet/Set' # 关键修正:用双引号包裹,直接嵌入单引号和变量 $Body = @{ OperationType = 'new' Number = "'$cd'" CdAspId = 'Z_CK_BUGFIX' CdType = 'CA_106_4' } | ConvertTo-Json $headers = @{ 'ContentType' = 'application/json' 'Accept' = 'application/json' 'APIKey' = 'abcdef' } Invoke-RestMethod -ContentType "application/json" -Uri $url -Method Post -Body $Body -Headers $headers
原理说明
- PowerShell中,双引号包裹的字符串会自动展开变量(
$cd会被替换为12000),同时直接写入的单引号会被当作普通字符保留,最终生成的JSON中Number字段值为"'12000'",即后端收到的是带单引号的字符串'12000'。 - 原脚本中的
"'$($cd)'"写法错误,会导致生成的JSON格式不符合预期,进而触发内部服务器错误。
内容的提问来源于stack exchange,提问作者gaurav sharma
相关产品推荐
相关产品推荐

