How to get response using WebClient in powershell

8.1k Views Asked by At

I saw the following code in stackoverflow :

$uri = "http://google.com"
$wc = New-Object System.Net.WebClient
$wc.UseDefaultCredentials = $true
$json = $wc.DownloadString($uri)

And it is working fine , but what I am wandering for, is that somehow I could store the status code of the URL I am hitting.

Actually when I am hitting a URL having status 404 , it is returning a exception for same.

Can anyone help me regarding how I can store the status or even if I can store the exception it is returning back.

2

There are 2 best solutions below

2
On

This should be a good starting point for you:

#requires -Version 3

$out = Invoke-WebRequest -Uri 'http://google.com' -UseDefaultCredentials -SessionVariable 'conn'

Then you can check $conn for connection details. $out will have the status, returns, etc. $out.StatusCode = 200 in this example.

0
On

I did some study and saw that the following method is working fine in powershell 2.0

$req = [system.Net.WebRequest]::Create($uri)
$req.UseDefaultCredentials = $true
try
{
$res = $req.GetResponse()
}
catch [System.Net.WebException]
{
$res = $_.Exception.Response
}
$int = [int]$res.StatusCode
echo $int

And this worked perfectly as per my requirement.