Check if URL is Reachable in PowerShell

PowerShell check if URL is reachable

Using Test-Connection Cmdlet

To check if URL is reachable in PowerShell:

  • Convert url to System.url object and get host property using Select-Object cmdlet.
  • Use Test-Connection cmd to check if host is reachable or not.

In the above code, the Test-Connection cmdlet sends an ICMP echo request to the hostname. First, the code sets the URL to be checked in the $url variable. Then, it uses the [System.Uri] class to convert the URL to a Uri object and selects the Host property of the Uri object using the Select-Object cmdlet and the -ExpandProperty parameter. This extracts only the hostname from the URL and assigns it to the $hostname variable.

Next, the Test-Connection cmdlet sends an ICMP echo request to the $hostname. The -ComputerName parameter specifies the hostname to ping, and the -Quiet parameter suppresses the output and only returns a Boolean value indicating whether the ping was successful. We will get True if the ping was successful; otherwise, False.

Using Invoke-WebRequest Cmdlet

Use the Invoke-WebRequest cmdlet to check if the URL is reachable in PowerShell.

In the above code, the response object code sets the URL to be checked in the $url variable and then uses the -Uri parameter of Invoke-WebRequest to specify the URL.

Additionally, the -UseBasicParsing parameter is used to speed up the process by avoiding full HTML parsing, and the -Method Head parameter is used to send a HEAD request instead of a GET request, which only retrieves the header information and not the entire content of the page.

The response object returned by Invoke-WebRequest contains a StatusCode property, which represents the HTTP status code returned by the server. For example, if the status code is 200, the request was successful, and the URL is reachable. In this case, the code prints a message to the console saying that the URL is reachable using the Write-Host cmdlet.

If the status code is anything other than 200, the request was unsuccessful. In this case, the code prints a message to the console saying that the URL is not reachable.

Based on the above solutions, these methods can be applied to various web-related tasks, such as monitoring web service availability or testing network connectivity. PowerShell automates this process, making your web services available when needed.

That’s all about how to check if URL is reachable in PowerShell.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *