我正在尝试编写一个powershell脚本(Powershell6和7),以便从一个带有JSON body的文本文件进行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 body)开头和结尾的引用。但是,如果我从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你知道我该怎么解决这个问题吗?
发布于 2020-09-24 06:08:57
解决方法是删除txt文件中的简单引号,并将以下代码添加到我的代码ConvertTo-Json -Depth 5中
https://stackoverflow.com/questions/63998857
复制相似问题