Test Website via HTTP request (Similarly as opening from a browser), get the response and implement logic around
Copy text below into a power shell session and execute to see the code in action.
# Snippet - Web - Test Website via Http Request # Core Snippet and Sample # www.PowerShellExamples.com # Test a Website using HTTP Request # Create object to store results $resultObj = New-Object -TypeName PSObject $resultObj | Add-Member -MemberType NoteProperty -Name Url -Value $url -PassThru | Add-Member -MemberType NoteProperty -Name Response -Value $null -PassThru | Add-Member -MemberType NoteProperty -Name ExitCode -Value "" -PassThru | Add-Member -MemberType NoteProperty -Name ExitMessage -Value "" $url = "https://google.com" try{ # Create the request. $HTTP_Request = [System.Net.WebRequest]::Create($url) # Get a response from the site. $HTTP_Response = $HTTP_Request.GetResponse() $resultObj.Response = $HTTP_Response if($resultObj.Response.Length -gt 500){ $resultObj.Response = $resultObj.Response.substring(0,500) } # get the HTTP code as an integer. $HTTP_Status = [int]$HTTP_Response.StatusCode If ($HTTP_Status -eq 200 -or $HTTP_Status -eq 401) { $resultObj.ExitCode = 0 $resultObj.ExitMessage = "Ok. Site is Active!" } Else { $resultObj.ExitCode = 2 $resultObj.ExitMessage = "The Site may be down, please check!" } # Finally, we clean up the http request by closing it. If ($HTTP_Response -ne $null) { $HTTP_Response.Close() } }catch{ if($_.Exception -like "*(401) Unauthorized*"){ $resultObj.Response = "Site is Visible.Reporting (401) Unauthorized,`r`n ( $($_.Exception.Message) )" $resultObj.ExitCode = 0 $resultObj.ExitMessage = "Ok" }else{ $resultObj.ExitCode = 2 $resultObj.ExitMessage = $_.Exception | Out-String } } $resultObj | out-string | Write-host
PS C:\> Url Response ExitCode ExitMessage --- -------- -------- ----------- https://google.com System.Net.HttpWebResponse 0 Ok. Site is Active!