Batch - Ping IP and execute different commands on return

17,307
ping -n 1 xxx.yyy.zzz.www | findstr TTL && start home.mp3
ping -n 1 xxx.yyy.zzz.www | findstr TTL || start alarm.mp3
Share:
17,307

Related videos on Youtube

Anton Johnsson
Author by

Anton Johnsson

Updated on November 22, 2022

Comments

  • Anton Johnsson
    Anton Johnsson over 1 year

    I'm trying to make (hopefully a simple) script that when run pings my mobile device. If the mobile is connected to the network it will execute one command and if not it will execute another.

    I've tried with the following command:

    ping -n 1 (The IP) >nul    
    IF ERRORLEVEL 0 GOTO safe    
    IF ERRORLEVEL 1 GOTO alarm
    
    :safe    
    start home.mp3    
    GOTO end
    
    :alarm    
    start alarm.mp3    
    GOTO end
    
    :end
    exit
    

    This actually worked once, but since then it doesn't work after the first ping. Is it something I'm missing? Perhaps there's an easier way of doing this?

    • uSlackr
      uSlackr almost 12 years
      FYI - the reason this doesn't work is because the ping command does not set the errorlevel based on the result of the ping. We used to have a command line tool called "alive" that did that.
  • Anton Johnsson
    Anton Johnsson almost 12 years
    This worked perfectly. Finally I can go to sleep. Thank you so much!!!
  • 030
    030 over 9 years
    @AntonJohnsson So this answered your question? Why did you not accept the answer?
  • Ed Mozley
    Ed Mozley about 2 years
    Adding -w 1000 is a nice optimisation as this will set the timeout at 1s (1000ms)