I know of a few good ways to build web clients in PowerShell: the .NET classes System.Net.WebClient and System.Net.HttpWebRequest, or the COM object Msxml2.XMLHTTP. From what I can tell, the only one which gives you access to the numeric status code (e.g. 200, 404), is the last, the COM object. The problem I have is that I don't like the way it works and I don't like relying on the COM object being there. I also know that from time to time Microsoft will decide to kill COM objects (ActiveX kill bits) due to security vulnerabilities and so on.
Is there another .NET method I'm missing? Is the status code in one of these other two objects and I just don't know how to get at it?
Use the [system. net. httpstatuscode] enumerated type.
To get the status code of an HTTP request made with the fetch method, access the status property on the response object. The response. status property contains the HTTP status code of the response, e.g. 200 for a successful response or 500 for a server error.
HTTP status codes are three-digit responses from the server to the browser-side request.
Using both x0n and joshua ewer's answers to come full circle with a code example, I hope that's not too bad form:
$url = 'http://google.com' $req = [system.Net.WebRequest]::Create($url) try { $res = $req.GetResponse() } catch [System.Net.WebException] { $res = $_.Exception.Response } $res.StatusCode #OK [int]$res.StatusCode #200
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With