Ping with [System.Net.WebRequest] failed

Hi, I have created the following test.ps1 file :

try {
    $url = "https://www.mql5.com"
    Write-Host "Pinging web address for server: $url ..."
    $request = [System.Net.WebRequest]::Create($url)
    $response = $request.GetResponse()
    Write-Host "Web Ping on $server Succeeded."   
} catch {
    Write-Host ("Web Ping on $url FAILED!!! The error was '{0}'." -f $_)
} finally {
    if ($response) {
        $response.Close()
        Remove-Variable response
    }
}

If I open a Windows Terminal in Admin mode and ping the website, it works, but if I launch :

PS C:\Users\Tom> powershell.exe -ExecutionPolicy Bypass -File c:\Users\Tom\Desktop\test.ps1

then I get this error msg:

Web Ping on https://www.mql5.com FAILED!!! The error was ‘Exception calling “GetResponse” with “0” argument(s): “The underlying connection was closed: The connection was closed unexpectedly.”’.

If I change the website with google, then it works.

What’s wrong???

Thanks!

vindiou,
Welcome to the forum. :wave:t4:

Is there a particular reason why you’re not using Invoke-Webrequest instead of the dotNet method?

There may be a rule or an external blocking device involved when it works for some addresses or for some accounts.

Some websites require a useragent so we simply give it one.

try {
    $url = "https://www.mql5.com"
    Write-Host "Pinging web address for server: $url ..."
    $request = [System.Net.WebRequest]::Create($url)
    $request.UserAgent = [Microsoft.PowerShell.Commands.PSUserAgent]::Chrome
    $response = $request.GetResponse()
    Write-Host "Web Ping on $url Succeeded."   
}
catch {
    Write-Host ("Web Ping on $url FAILED!!! The error was '{0}'." -f $_)
}
finally {
    if ($response) {
        $response.Close()
        Remove-Variable response
    }
}

As you can see, I chose chrome. But you could pick your preferred browser agent.

2 Likes

No, I just don’t know how to use Invoke-Webrequest, can you please show me how? thx

Thanks it works perfectly.

You always start by reading the help for the cmdlets you’re about to use. Read it completely including the examples please:

Usually you start with searching the the internet with your favorite search enginge for answers and examples. :wink:

Create task-schedule that will start your script as an administrator. As event trigger you can set application eventID e.g 69.
Create shortcut or batch/powershell file that will write-eventlog application with your eventID.

When you run shortcut, event id will be writed in your event log and this will start your task with admin priviliages.

Or you can simply use schtasks run to run the scheduled task you want. :wink: