5

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
}

私も試しました:

LogWrite "StatusCode:" $Response.Exception.Response.StatusCode.value__ 

この質問 (およびその他のリンク) を使用しました: Invoke-Restmethod: how do I get the return code?

これを解決しようとして、私のログには「SuccessOnCall」と書かれていますが、StatusCode は空白です。

ありがとうございました。

4

2 に答える 2

8

select-object でパイプを試みましたか?

Invoke-WebRequest -Uri apiEndpoint -UseBasicParsing | Select-Object StatusCode

出力

StatusCode
 ----------
   200

または単にステータスコードを取得する

Invoke-WebRequest -Uri apiEndpoint -UseBasicParsing | Select-Object -Expand StatusCode

出力

200

失敗したケースを処理するには、PowerShell v#7 +-SkipHttpErrorCheck パラメーター$Errorを含めるか、配列を使用して最新のエラーを取得し、それに応じてプロパティにアクセス する必要がある場合があります。

于 2020-05-21T18:55:59.553 に答える