if else based on output of invoke-webrequest in PS

powershell invoke-webrequest headers
powershell invoke-webrequest example
invoke-webrequest vs invoke-restmethod
powershell invoke-webrequest download file
invoke-webrequest usebasicparsing
invoke-webrequest https
invoke-webrequest outfile
invoke-webrequest get

Can someone help me capture only the StatusCode of invoke-webrequest below so that I can determine if a site is up (200) or down (any other code). I think essentially an if else statement will be needed.

NOTE: I don't need the output of invoke-webrequest. This is the code I'm running now with: .\websiteCheck.ps1 https://google.com

$url = $args[0]

[Net.ServicePointManager]::SecurityProtocol = "Tls11"

invoke-webrequest -uri $url -DisableKeepAlive -UseBasicParsing -Method head

which returns a lot more info to work with than I need:

StatusCode        : 200
StatusDescription : OK
Content           :
RawContent        : HTTP/1.1 200 OK
                X-XSS-Protection: 1; mode=block
                X-Frame-Options: SAMEORIGIN
                Cache-Control: private, max-age=0
                Content-Type: text/html; charset=UTF-8
                Date: Wed, 20 Feb 2019 05:55:14 GMT
                Expires: ...
Forms             :
Headers           : {[X-XSS-Protection, 1; mode=block], [X-Frame-Options, SAMEORIGIN], [Cache-Control, private,
                max-age=0], [Content-Type, text/html; charset=UTF-8]...}
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        :
RawContentLength  : 0

I'd just like to do something like:

if StatusCode = 200 write-host "The site is up" else write-host "The site is down"

This must be based on invoke-webrequest and not something like [Net.HttpWebRequest] $req = [Net.WebRequest]::Create($url) because otherwise it doesn't work properly with url's that do multiple redirects.

There are more status codes that can be returned. See HTTP Status Codes.

So maybe a bit more fine-grained script would be a better choice?

$uri = $args[0]
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

try{
    $status = [int](Invoke-WebRequest $uri -UseBasicParsing -DisableKeepAlive -Method Head).StatusCode
    switch ($status) {
        {$_ -ge 100 -and $_ -lt 200}  { Write-Output "The site is up. Statuscode: $status"; break }
        {$_ -ge 200 -and $_ -lt 300}  { Write-Output "The site is up. Statuscode: $status"; break }
        {$_ -ge 300 -and $_ -lt 400}  { Write-Output "The site is redirected. Statuscode: $status"; break }
        {$_ -ge 400 -and $_ -lt 500}  { Write-Output "Client error. Statuscode: $status"; break }
        {$_ -ge 500 -and $_ -lt 600}  { Write-Output "Server error. Statuscode: $status"; break }
        default { Write-Output "The site returned an unhandled status code. Statuscode: $status"}
    }
}
catch {
    Write-Error "An error occurred on Invoke-WebRequest.`r`n$($_.Exception.Message)"
}

Instead of the Invoke-WebRequest you could also use [System.Net.WebRequest]. Something like:

$uri = $args[0]
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

try{
    # Web request
    $res = ([System.Net.WebRequest]::Create($uri)).GetResponse()
}
catch {
    $res = $_.Exception.Response
}
$status = [int]$res.StatusCode
switch ($status) {
    {$_ -ge 100 -and $_ -lt 200}  { Write-Output "The site is up. Statuscode: $status"; break }
    {$_ -ge 200 -and $_ -lt 300}  { Write-Output "The site is up. Statuscode: $status"; break }
    {$_ -ge 300 -and $_ -lt 400}  { Write-Output "The site is redirected. Statuscode: $status"; break }
    {$_ -ge 400 -and $_ -lt 500}  { Write-Output "Client error. Statuscode: $status"; break }
    {$_ -ge 500 -and $_ -lt 600}  { Write-Output "Server error. Statuscode: $status"; break }
    default { Write-Output "An unhandled error occurred. Statuscode: $status"}
}
# Dispose response if available
if($res){ $res.Dispose() }

Really simple if/else based on output of a iwr : PowerShell, Really simple if/else based on output of a iwr. Hi guys. I need to send an try { $ req = Invoke-WebRequest -Uri "url.com/employed" $stat = $req.StatusCode } catch { "Page Reminder: always check PS code from 3rd parties. Edit: Shout out to� The Invoke-WebRequest cmdlet sends HTTP and HTTPS requests to a web page or web service. It parses the response and returns collections of links, images, and other significant HTML elements. This cmdlet was introduced in PowerShell 3.0. Beginning in PowerShell 7.0, Invoke-WebRequest supports proxy configuration defined by environment variables. See the Notes section of this article.

This might work

$uri = $args[0]

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

try{
    if((Invoke-WebRequest $uri -UseBasicParsing -DisableKeepAlive -Method Head).StatusCode -eq 200)
    {
        Write-Output "The site is up."
    }
}
catch {
    Write-Output "The site is down."
}

HTTP requests with PowerShell's Invoke-WebRequest – by Example , Surely Windows PowerShell contains an If statement. In the DemoIf.ps1 script, we are checking whether the variable $a is equal to 5. This is� Invoke-WebRequest creates the session and saves it in the variable. In subsequent commands, use the variable as the value of the WebSession parameter. You cannot use the SessionVariable and WebSession parameters in the same command. The Invoke-WebRequest cmdlet sends HTTP, HTTPS, FTP, and FILE requests to a web page or web service.

Use property dereferencesmember access operator and if to do the work.

$uri = $args[0]

[Net.ServicePointManager]::SecurityProtocol = ([Net.SecurityProtocolType]::Tls12, [Net.SecurityProtocolType]::Tls11, [Net.SecurityProtocolType]::Tls, [Net.SecurityProtocolType]::Ssl3)

try {
    if ((Invoke-WebRequest $uri -UseBasicParsing -DisableKeepAlive -Method Head).StatusCode -eq 200) {
        Write-Host "The site is up."
    }
    else {
        Write-Host "The site is down."
    }
}
catch {
    Write-Host "The site is down."
}

The script above has been modified, some comments below are obsolete.

Hey, Scripting Guy! How Can I Use the If Statement in Windows , A quick lesson in using Try and Catch with Invoke-WebRequest cmdlets for such as 403 Forbidden or 405 Method Not Allowed – when invoked. To combat this, I've started using Try and Catch statements in my API calls,� If you pass a URI to Invoke-WebRequest, it won’t just display the HTML code of the web page. Instead, it will show you formatted output of various properties of the corresponding web request. Instead, it will show you formatted output of various properties of the corresponding web request.

Invoke-WebRequest (Microsoft.PowerShell.Utility), If you're having a hard time parsing the data from Invoke-WebRequest, controlling All with logging and results output for later review and verification. Now we can create a new PS Credential object to store our username, and password Command #Use the Switch statement to take different actions based on the job's� Note: I don't know if the change - a breaking one - was intentional. If so, it's worth documenting. Arguably, the new behavior is less surprising. Update: The change in behavior seems to come from the underlying [System.Net.HttpWebReques

Using Try and Catch with PowerShell's Invoke-WebRequest, But, what happens when you're trying to use a modern REST API via They think that you know exactly what else is required to get the cURL with REST APIs the equivalent of cURL in PowerShell is Invoke-RestMethod. I am using invoke-webrequest to use a websession to try and connect to a local thruk omd instance. I am trying to correlate the forms the best i can from the examples but when I try and submit the web session the output just keeps going back to the login page. This is the following code I run:

getting started — Ninja PowerShell Blog — The Ginger Ninja, The first thing the if statement does is evaluate the expression in parentheses. It was $true and would have executed the Write-Output command inside the scriptblock. PowerShell has its own wildcard based pattern matching syntax and you can use it with the -like operator. PS> 1,2,3,4 -eq 3 3. There are more detailed lists of questions, based on the problem details, in the above linked issue. Otherwise, too: definitely contribute to the issue's conversation, give more reaction/thumbs-up emojis to the OP of the issue and to any other helpful comments within the issue conversation.

Comments
  • Thanks Theo! Works well but I needed to add one more separate Write-Host that would also be displayed with your write-output and I didn't know how to do that. I prefer your script as it's more detailed but I had to go with Kexy's as it was easy for me to add those write-host messages there.
  • @yorkman Sure, no worries. It is extremely easy however to add extra Write-Host messages before the break commands inside the switch block.
  • Thanks I figured that but where exactly? The switch block has 5 different {$_ -ge's and I want to write-host something for each one. One for the 100 to 200 range, another for 200-300 etc. Do I just add it at the end of each write-output but before the break, and on a new llne? So { write-output "the site is up" then on a new line write-host "1"; break } ?
  • Thank you Theo! Out of all the code samples out there yours is the only one that works perfectly regardless of the URL status. I really appreciate your efforts.
  • @yorkman Glad it worked for you. If you feel my answer solved your problem, please consider accepting the answer by clicking ✓ on the left. See How to accept SO answers. This will help others with a similar question finding it more easily.
  • Thanks. The problem with that is it displays errors if the url doesn't resolve like: google.com77 instead of "The site is down."
  • Also it returns: Invoke-WebRequest : The remote server returned an error: (404) Not Found. if my URL is like PrivateURL.com/index?RedirectUrl=%2F While this example is using a bogus URL the page of the real URL does open in a browser.
  • @yorkman Updated per your request, it now covers these situations.
  • Awesome! Thanks Kexy. Works great but I did have to use this instead: [Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls, ssl3" to support all the various protocols the site may be using.
  • @yorkman I thought it was some restrictions around TLS versions :P