-
ping bat scipt
I am trying to write a simple batch script that will ping a machine on the local network (10.0.0.2) and net send the server (10.0.0.1) the result
-however this appears to be failing, can anyone point out why
PING 10.0.0.2 ¦ FIND "TTL" >NUL
IF ERRORLEVEL 1 net send 10.0.0.1 No Response
IF ERRORLEVEL 0 net send 10.0.0.1 Responded
is there something wrong with my logic - i dont do much batch scripting
thanks
-
"IF ERRORLEVEL n" specifies a true condition if the last program run returned an exit code equal to or greater than the number specified. Therefore, your bat would run both net send commands when 0 is returned. We can use a dreaded goto to avoid this problem. I found that the FIND command is not needed as ping will return 0 on success and 1 on failure.
Code:
@ping 10.0.0.2 > nul
@IF ERRORLEVEL 1 GOTO dead
@IF ERRORLEVEL 0 GOTO alive
:dead
@net send 10.0.0.1 Dead
@ECHO Dead
@GOTO end
:alive
@net send 10.0.0.1 Alive
@ECHO Alive
@GOTO end
:end
@ECHO Goodbye
Batch Files Reference and Examples
-
i tried that script and it doesnt net send anything. I aslo tried it replacing net send with echo and then a message but that doesnt work either. I also cant seem to print the value of ERRORLEVEL
echo ERRORLEVEL
can anyone point out why this is not working?
-
> PING 10.0.0.2 ¦ FIND "TTL" >NUL
What are you trying to get the exit status from - the ping command or the find command?
This problem gets interesting enough in proper unix shells, so I can imagine the same thing in a windows shell to be hopeless if the answer isn't the one you're given.
-
>> i tried that script and it doesnt net send anything. <<
Yes it did. Please make sure net send is working by trying it on the command line. By default XP SP2 disables the Messenger service which is required to receive net send messages. You can enable the Messenger service by going to Control Panel->Administrative Services->Services and enabling the Messenger service.
However, the script I posted was sending twice since I forgot that the net send command would alter the errorlevel. The script, as amended above, has been successfully tested on my computer.
>> I also cant seem to print the value of ERRORLEVEL <<
When echoing, variables must be enclosed in %.
-
It wasnt a problem with the messenger or the script, i'd made a small mistake changing part of the message. It all works great, thanks.