Powershell – Test URL “ping” from command line


To totally unlock this section you need to Log-in

The following scenario could be useful for those that need to regularly monitor the response type of specifc URL or URLs; this can be done quite easily by using Powershell. In fact, for people that have PowerShell 3 or later (introduced in Windows Server 2012+ or Windows Server 2008 R2 with the Windows Management Framework 4.0 update), so basically everyone using Windows 10 and Windows Server 2016 and up, this can be achieved by executing the following one-liner instead of invoking System.Net.WebRequest:

$statusCode = wget https://www.heelpbook.net -Method head | % {$_.StatusCode}

Take note that % is alias for ForEach-Object. The character $ designates a variable. The _ character, when following a $, is an alias for $PSItem, which is an automatic variable (man about_Automatic_Variables) that contains the current object in the pipeline object.

Which brings us to the "pipe" | (man about_Pipelines) and allows the output of the previous command to be used as input for the following command. So the full translation of the above command is the following:

$variable = Invoke-WebRequest https://www.heelpbook.net -Method head | ForEach-Object {$PSItem.StatusCode}

We can obviously use the normal Invoke-WebRequest command. A problem that could be raised by using it (and the above example) on a Server Core machine is that it could return an error:

Invoke-WebRequest "https://www.heelpbook.net/"  | Select-Object StatusCode,StatusDescription,Content

Error message:
The response content cannot be parsed because the Internet Explorer engine is not available, or Internet Explorer’s first-launch configuration is not complete. Specify the UseBasicParsing parameter and try again.

To fix this we just have to use the parameter -UseBasicParsing:

Invoke-WebRequest "https://www.heelpbook.net/" -UseBasicParsing | Select-Object statuscode,statusdescription,content

You can run this command also remotely by adding this in Scriptblock and by using the following approach:

$server = "Server01"
$url = "https://www.heelpbook.net/"
$HttpQuery = Invoke-command $Server -Scriptblock { param($url)Invoke-WebRequest $url -UseBasicParsing | Select-Object StatusCode,StatusDescription,Content } -ArgumentList $Url

The following script can be use to execute a URL check from multiple machines. Results will be added to an array and displayed in new pop-up window.

##### Variables ######## 
$Report = @()
$Url = "https://www.heelpbook.net/"
$Servers = Get-Content "C:\Users\$env:username\Desktop\Systems.txt"
##### Variables ########

ForEach ($Server in $Servers) {
    $HttpQuery = $Object = $null
    $Server = $Server.trim()
     
    Write-Host "Processing $Server"
    Try {
        $HttpQuery = Invoke-command $Server -Scriptblock{ param($Url)Invoke-WebRequest $Url -UseBasicParsing | Select-Object StatusCode,StatusDescription,Content } -ArgumentList $Url

        If ($HttpQuery) {
            $Object = New-Object PSObject -Property ([ordered]@{ 
  
                ServerName              = $Server
                URL                     = $url
                Status                  = $HttpQuery.statusdescription
                StatusCode              = $HttpQuery.statuscode
                Content                 = $HttpQuery.content
                 
            })
            $Report += $Object
        }
    }
    Catch {
        $_.Exception.Message
        Continue
    }
}
 
$Report | Out-GridView -Title "URL Check Results"

The below is a function approach that can be used to integrate this check in other Powershell based projects. The function use the Invoke-WebRequest cmdlet as his core.

function Get-UrlStatusCode([string] $Url)
{
    try
    {
        (Invoke-WebRequest -Uri $Url -UseBasicParsing -Method head -DisableKeepAlive).StatusCode
    }
    catch [Net.WebException]
    {
        [int]$_.Exception.Response.StatusCode
    }
}

#### This is a typical usage of the function defined above #####
$statusCode = Get-UrlStatusCode 'https://heelpbook.net/'

A specific case: HTTPS with IP address

The above approaches can be used also for HTTPS URLs but, if we need, for some reason, to execute simple https tests for an application based on server IP addresses, like for example "https://192.168.10.20/TestURL/" we need to be aware that this kind of test will return success or failed value. To test this we can just use .Net class New-Object System.Net.WebClient, as shown in the below script code:

$Results = @()
$Servers = Get-Content "C:\Users\$env:username\Desktop\Systems.txt"
$WebClient = New-Object System.Net.WebClient
 
Foreach($Computername in $Servers) {
    $Computername = $Computername.Trim()
    Write-Host "Processing $Computername"
    $Object = $FQDN = $Ip = $URLTest = $Content = $ip = $TestUrl = $null
    $FQDN = ([System.Net.Dns]::GetHostByName(("$Computername")))
 
    If(!$FQDN) {
        Write-Warning "$Computername does not exist"
    }
    Else {
 
        Try {
            $Ip = $FQDN.AddressList[0].IPAddressToString
            $TestUrl = "https://$ip/TestURL/"
 
            [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
            $URLTest = $WebClient.DownloadString($TestUrl)
 
            If($URLTest) {
                $Content = (($URLTest -split '\n') | Where-Object {$_ -match "success|failed"}).Trim()
                $Object = New-Object PSObject -Property ([ordered]@{ 
 
                    Server                  = $Computername
                    IPAddress               = $Ip
                    TestURL                 = $TestUrl
                    Content                 = $Content
                 
                })
                $Results += $Object
            }
        }
        Catch {
            $_.Exception.Message
            Continue
        }
    }
}
 
$Results | Out-GridView -Title "Test results"
$Results  | Export-Csv -Path C:\users\$env:username\desktop\TestResults.csv -NoTypeInformation


Summary
Article Name
Powershell - Test URL "ping" from command line
Description
The following scenario could be useful for those that need to regularly monitor the response type of specifc URL or URLs; this can be done quite easily by using Powershell. The approach can be easily integrated in functions and automated/scheduled scripts to get a periodic status of the URLs monitored.
Author
Publisher Name
Heelpbook.net