Trying to Run VBS MsgBox from Batch File

Stan Jx Source

I have a batch file with the following code:

   @echo off

:START

ping 192.168.9.19 -n 1 -w 1800000 > nul 2>&1


if errorlevel 1   taskkill /F /IM excel.exe > nul 2>&1



Timeout /t 1 > nul 2>&1
@set errorlevel = 0

GOTO START

I need to add a line on errorlevel 1 to open a vbs message box MsgBox.vbs

I tried adding the following line but it did not work:

wscript "C:\Users\James.Jayesuria\Desktop\MsgBox.vbs" < nul 2>&1

I added it like such:

@echo off

:START

ping 192.168.9.19 -n 1 -w 1800000 > nul 2>&1


if errorlevel 1   taskkill /F /IM excel.exe > nul 2>&1
wscript "C:\Users\James.Jayesuria\Desktop\MsgBox.vbs"


Timeout /t 1 > nul 2>&1
@set errorlevel = 0

GOTO START

Would appreciate if someone could help me correct the code so the msgbox would pop up. When I run a bat file with only that code line the error msg pops up but when I try to add it to the network code it doesn't work

batch-filevbscriptping

Answers

answered 2 years ago NineBerry #1

The parameter -w 1800000 tells the ping command to wait for 1800000 milliseconds (= 30 minutes) before it fails when it cannot reach the host.

If you are patient enough and wait for half an hour, you will see the message box. In fact, you will also see it when the ping is successful, because the line calling the wscript command is executed without condition. If you have multiple commands that you only want to execute on the condition errorlevel 1, you have to include them in parenthesis.

Adapted code with

  • Only use timeout of 10 seconds in ping
  • Show Messagebox only when ping fails
  • you don't need to reset errorlevel. That happens automatically
  • Use waiting period of 10 seconds between ping attempts to save computing ressources

When you execute it while the ip cannot be reached, you have to wait for 10 seconds, before the message box is shown.


@echo off

:START

REM Try to ping with timeout of 10 seconds
ping 192.168.9.19 -n 1 -w 10000 > nul 2>&1

REM When ping fails, kill excel and show messagebox
if errorlevel 1 ( 
    taskkill /F /IM excel.exe > nul 2>&1
    wscript "C:\Users\James.Jayesuria\Desktop\MsgBox.vbs"
)

REM Wait 10 seconds between ping attempts
Timeout /t 10 > nul 2>&1

GOTO START

comments powered by Disqus