我正在尝试编写一个 powershell 脚本(powershell 6 和 7)以从带有 JSON 正文的文本文件中进行 REST 调用 API。这是我的代码:
$uri = 'URI'
$json = Get-Content 'TXT_FILE_WITH_JSON_BODY' | Out-String | ConvertFrom-Json | ConvertTo-Json | %{[regex]::Unescape($_)}
$username = 'USER'
$password = 'PASSWORD'
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))
Invoke-RestMethod -Method POST -SkipCertificateCheck -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} $uri -body $json -ContentType "application/json"
我的txt文件:
'{
"apiversion": "3.0",
"process": {
"profileId": "ID",
"jobType": "TYPE",
"origin": "ORIGIN",
"processWhileGrowing": true
},
"jobSource": {
"sources": [
{
"uri": "\\\\\\\\10.22.6.250\\\\share\\\\test\\\\TEST01.mov"
}
],
"metadata": [
{
"name": "Description",
"value": "Bla bla bla"
},
{
"name": "title",
"value": "Title"
},
{
"name": "channel",
"value": "SRV1"
},
,
{
"name": "type",
"value": "TYPE01"
},
{
"name": "source",
"value": "SOURCE01"
}
]
}
}
'
然后当我执行我的脚本时,我得到了这个:
PS F:\Desktop> .\test01.ps1
Invoke-RestMethod: F:\Desktop\test01.ps1:6
Line |
6 | Invoke-RestMethod -Method POST -SkipCertificateCheck -Headers @{Autho …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| {
"status": "HTTP_ERROR",
"message": "SERVER_ERROR",
"message_detail": null
}
我的第一个想法是我的 REST API 对我的 txt 文件(json 正文)开头和结尾的引用没有很好的响应。但是,如果我从我的 txt 文件中删除引号,Powershell 会说以下内容:
PS C:\Users\Brice> F:\Desktop\jsonconvert.ps1
ConvertFrom-Json : Invalid JSON primitive: .
At F:\Desktop\jsonconvert.ps1:1 char:63
+ ... nt 'F:\Desktop\1.txt' | Out-String | ConvertFrom-Json | Conve ...
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [ConvertFrom-Json], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
知道如何解决这个问题吗?