-2

The question may sound stupid but I 've been trying to do it for hours now.

The thing is that, I want a batch file to check for internet connction every 30 seconds and if there is no connection, I want it to check for it again.

If the connection is available, I want it to start a program let's say Notepad.exe.

I can also use powershell, but I am a bit unfamiliar with that but I would be glad if it colud do the job.

  • 1
    Welcome to Stackoverflow. Please include the code you've tried in your question, and tell us what problems you had with it. – marsze Nov 02 '20 at 12:32
  • You could try something using "ping". This should work with batch files as well as powershell. Here's a link to something similar: https://stackoverflow.com/a/49656667/5594257 – adam Nov 02 '20 at 12:33
  • Here is a HTA named as [Check_Internet_Connection.hta](https://pastebin.com/yyewJYwW) – Hackoo Nov 02 '20 at 13:01

3 Answers3

3

You could use Test-Connection to check if you can reach a certain website. This is basically the powershell equivalent of ping.

while (-not (Test-Connection google.com -Count 1 -Quiet)) {
    Start-Sleep -Seconds 30
}
Start-Process notepad.exe
marsze
  • 15,079
  • 5
  • 45
  • 61
  • 1
    Note: You can also use ``(ping -t google.fr -n 1).Count -eq "1"`` in your condition – Xiaojiba Nov 02 '20 at 12:51
  • 1
    @Xiaojiba That is correct. However when I have the luxury to use powershell instead of batch, using a cmdlet is a lot more convenient. – marsze Nov 02 '20 at 12:53
1

The usual option is to decide for yourself how an active internet connection should look and act like and check accordingly. One way would be to use ping or Test-Connection, however that won't tell you when something other than DNS or ICMP is broken. You could also download a small resource somewhere and if it succeeds, an internet connection is apparently present. This could be done with curl, wget, or Invoke-WebRequest.

In a batch file you'd most likely check the exit code of the command (via if errorlevel or %errorlevel%) or just chain commands together with || and &&.

In PowerShell you can usually deduce failure or success a lot easier when using the respective cmdlets.

Joey
  • 344,408
  • 85
  • 689
  • 683
1

Using basic ping, but considering that ping is for diagnostics and does not get priority.

@echo off
:try
(ping 8.8.8.8 && start notepad)>nul 2>&1 || echo No connection
(timeout 30 /NOBREAK)>nul
goto :try

or by using curl:

@echo off
:try
(curl google.com && start notepad)>nul 2>&1 || echo No connection
(timeout 30 /NOBREAK)>nul
goto :try
Gerhard
  • 22,678
  • 7
  • 27
  • 43
  • 1
    Good work, it's nice to see the batch/cmd version of this. Reminds me why I love Powershell. – marsze Nov 02 '20 at 14:15