And*_*é G 5 rest powershell logging invoke-webrequest
我需要使用 Power Shell 从请求中获取成功和/或错误状态代码。我总是得到一个空白状态。
我尝试过 Invoke-WebRequest 和 Invoke-RestMethod。我已成功通话,但找不到获取状态代码的方法。
这里是如何写的:
$resource = "some url"
$Logfile = "C:/path/log.log"
function LogWrite
{
Param([string]$logstring)
Add-content $logfile -value $logstring
}
Try
{
$Response = Invoke-WebRequest -Method Post -Uri $resource
Write-Output("Success.")
LogWrite $Date
LogWrite SuccessOnCall
LogWrite $Response.StatusCode
}
Catch
{
$ErrorMessage = $_.Exception.Message
Write-Output($ErrorMessage)
$FailedItem = $_.Exception
Write-Output($FailedItem)
LogWrite $Date
LogWrite ErrorOnCall
LogWrite $ErrorMessage
Break
}
Run Code Online (Sandbox Code Playgroud)
我也试过:
LogWrite "StatusCode:" $Response.Exception.Response.StatusCode.value__
Run Code Online (Sandbox Code Playgroud)
我使用了这个问题(和其他链接):Invoke-Restmethod: how to get the return code?
试图解决这个问题,我的日志确实写了“SuccessOnCall”,但 StatusCode 为空。
谢谢你。
您是否尝试使用 select-object 进行管道传输?
Invoke-WebRequest -Uri apiEndpoint -UseBasicParsing | Select-Object StatusCode
Run Code Online (Sandbox Code Playgroud)
输出
StatusCode
----------
200
Run Code Online (Sandbox Code Playgroud)
或者只是为了获取状态代码
Invoke-WebRequest -Uri apiEndpoint -UseBasicParsing | Select-Object -Expand StatusCode
Run Code Online (Sandbox Code Playgroud)
输出
200
Run Code Online (Sandbox Code Playgroud)
要处理不成功的情况,请在 PowerShell v#7 + 包含-SkipHttpErrorCheck 参数,
或者您可能需要使用$Error数组来获取最新的错误并相应地访问属性。
| 归档时间: |
|
| 查看次数: |
9530 次 |
| 最近记录: |