Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
941 views
in Technique[技术] by (71.8m points)

powershell - if else based on output of invoke-webrequest in PS

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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() }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...