編集:私が最初に質問を誤解し、それはあなたがHttpWebResponse.GetResponseHeader()
メソッドを使用して、レスポンスヘッダを取得できることが判明しました。例外が発生した場合は、HttpWebRequest.GetResponse()
方法は$null
を返し、あなたはそれにGetResponseHeader()
を呼び出すことができるように、HttpWebResponseのオブジェクトを取得するには、このコードを使用する必要があります。
# If an exception occurs, get the HttpWebResponse object from the WebException object
$HttpWebResponse = $Error[0].Exception.InnerException.Response;
私は「あなたかなり確信していますSystem.Net.WebClient
オブジェクトの代わりにSystem.Net.HttpWebRequest
を使用します。ここでは、おそらく既に持っているものと同様の例です:
# Create a HttpWebRequest using the Create() static method
$HttpWebRequest = [System.Net.HttpWebRequest]::Create("http://www.google.com/");
# Get an HttpWebResponse object
$HttpWebResponse = $HttpWebRequest.GetResponse();
# Get the integer value of the HttpStatusCode enumeration
Write-Host -Object $HttpWebResponse.StatusCode.value__;
のGetResponse()メソッドは、HttpStatusCode
.NET列挙型の値を指すStatusCode
という名前のプロパティがありHttpWebResponse
オブジェクトを返します。列挙型への参照を取得したら、value__
プロパティを使用して、返された列挙型の値に関連付けられている整数を取得します。
GetResponse()
メソッドからヌル値を取得した場合は、catch {..}ブロックで最新のエラーメッセージを参照したいと思うでしょう。 Exception.ErrorRecord
プロパティが最も役立ちます。
try {
$HttpWebResponse = $null;
$HttpWebRequest = [System.Net.HttpWebRequest]::Create("http://www.asdf.com/asdf");
$HttpWebResponse = $HttpWebRequest.GetResponse();
if ($HttpWebResponse) {
Write-Host -Object $HttpWebResponse.StatusCode.value__;
Write-Host -Object $HttpWebResponse.GetResponseHeader("X-Detailed-Error");
}
}
catch {
$ErrorMessage = $Error[0].Exception.ErrorRecord.Exception.Message;
$Matched = ($ErrorMessage -match '[0-9]{3}')
if ($Matched) {
Write-Host -Object ('HTTP status code was {0} ({1})' -f $HttpStatusCode, $matches.0);
}
else {
Write-Host -Object $ErrorMessage;
}
$HttpWebResponse = $Error[0].Exception.InnerException.Response;
$HttpWebResponse.GetResponseHeader("X-Detailed-Error");
}
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
http://msdn.microsoft.com/en-us/library/system.net.httpstatuscode.aspx
http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.aspx
すでに例外オブジェクトをキャッチし、$ _。Exception.Messageプロパティを見たことがありますか?そして$ _。Exceptionオブジェクトを調べましたか? –