小编And*_*é G的帖子

如何从 PowerShell 中的请求中获取 StatusCode

我需要使用 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 为空。

谢谢你。

rest powershell logging invoke-webrequest

5
推荐指数
1
解决办法
9530
查看次数

标签 统计

invoke-webrequest ×1

logging ×1

powershell ×1

rest ×1