gpt4 book ai didi

powershell - 如何通过Power Shell Invoke-RestMethod获取返回值

转载 作者:行者123 更新时间:2023-12-03 00:45:34 25 4
gpt4 key购买 nike

在Powershell中,我可以执行这种命令。但是,如何获得一些返回值以验证此调用是否成功失败?

我想得到一些返回结果并检查做类似的任务

$url = ("http://localhost:5000", $path -join "")
Invoke-RestMethod -Method Get -Uri $url -Headers $bearerHeader

要么,
Invoke-RestMethod -Method Post -Uri $url  -ContentType "application/json" -Body $bod

如果我能得到一些返回,我可以做这样的事情:
if($resp -eq $false)
{
Write-Host "Failed to upload file:" $upload.GetPath() -ForegroundColor "Red";
return;
}

最佳答案

Invoke-RestMethod当前不像Invoke-WebRequest那样返回响应代码。您可以改用Invoke-WebRequest,也可以使用Try..Catch测试异常:

Try {
Invoke-RestMethod -Method Post -Uri $url -ContentType "application/json" -Body $bod -ErrorAction Stop
} Catch {
Write-Host "Failed to upload file:" $upload.GetPath() -ForegroundColor "Red";
}

从PowerShell 6(Core)开始,您具有 -ResponseHeaderVariableInvoke-RestMethod参数,即使连接成功,即使响应为空,也可以通过该参数获取数据。

例如:
~\Documents> Invoke-RestMethod http://xkcd.com/info.0.json -ResponseHeadersVariable Response

~\Documents> $Response

Key Value
--- -----
Cache-Control {max-age=300}
Connection {keep-alive}
Date {Fri, 12 Jan 2018 17:24:30 GMT}
Via {1.1 varnish}
Accept-Ranges {bytes}
Age {115}
ETag {"5a5846d2-1a9"}
Server {nginx}
Vary {Accept-Encoding}
X-Served-By {cache-lhr6327-LHR}
X-Cache {HIT}
X-Cache-Hits {1}
X-Timer {S1515777871.992127,VS0,VE3}
Content-Length {425}
Content-Type {application/json}
Expires {Fri, 12 Jan 2018 05:31:14 GMT}
Last-Modified {Fri, 12 Jan 2018 05:25:38 GMT}

关于powershell - 如何通过Power Shell Invoke-RestMethod获取返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48231003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com