Bunu dene:
try { $response = Invoke-WebRequest http:
$_.Exception.Response.StatusCode.Value__}
Bunun bir istisna yaratması biraz serseri ama bu böyle.
Yorum başına güncelleme
Bu tür hataların hala geçerli bir yanıt döndürdüğünden emin olmak için, bu tür istisnaları yakalayabilir WebExceptionve ilgili olanları getirebilirsiniz Response.
İstisnanın cevabı tipte olduğu için System.Net.HttpWebResponse, başarılı bir Invoke-WebRequestçağrının cevabı tipte Microsoft.PowerShell.Commands.HtmlWebResponseObjectolduğu için, her iki senaryodan da uyumlu bir tip döndürmek için BaseResponse, yine tipte olan başarılı cevapları almamız gerekir System.Net.HttpWebResponse.
Bu yeni yanıt türünün durum kodu [system.net.httpstatuscode], basit bir tamsayıdan ziyade bir enum türündedir , bu nedenle, onu int'e dönüştürmeniz veya Value__sayısal kodu almak için yukarıda açıklandığı gibi özelliğine erişmeniz gerekir .
$response = try {
(Invoke-WebRequest -Uri 'localhost/foo' -ErrorAction Stop).BaseResponse
} catch [System.Net.WebException] {
Write-Verbose "An exception was caught: $($_.Exception.Message)"
$_.Exception.Response
}
$statusCodeInt = [int]$response.BaseResponse.StatusCode
$statusCodeInt = $response.BaseResponse.StatusCode.Value__