0

我正在编写一个 Powershell 脚本,该脚本需要轮询 API 方法以查看它是否可用。如果这个 API 要返回 400 的东西,我该如何处理呢?

考虑这段代码:

$response = Invoke-WebRequest -uri $uri -ContentType "application/json" -Method Get

$status = $response.StatusCode
Write-Output "`nStatus code is $status."

如果来自服务器的响应是 400 Bad Request,Powershell 会以意想不到的方式运行:

Invoke-WebRequest :“错误请求的某些原因。” 在 C:\SomePath\SomeScript.ps1:19 char:26 + $response = Invoke-WebRequest -uri $uri -ContentType "appl ... + ~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest: HttpWebRequest) [Invoke-WebRequest], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

响应状态码是 。

请注意,状态代码不可用,主要是因为$response不包含任何内容。我需要$response填充来自请求的响应的详细信息,以便脚本可以决定做某事。我怎样才能捕捉到这些信息?

4

0 回答 0