I am attempting to write a script that will check to see if a computer is on my LAN before running the rest of my script. It is a simple backup script using robocopy but I would like it to output a file based on whether it was successful or not. This is what I have.
set machine=userbox
ping -n 1 %machine% > nul
if errorlevel 1 goto BAD
goto GOOD
:GOOD
robocopy source destination
echo "backup complete" > c:\scripts\backupgood-%machine%.log
shutdown /s /m \\%machine% /t 600
goto END
:BAD
echo "Computer not on" > c:\scripts\%machine%-offline.log
:END
Right now the script is not detecting whether the system is on or not and it is assuming it is on and continues with the script as if the machine was able to be pinged.
Can someone point out why the error is not passing or perhaps someone has a better way of determining if a system is online.
Thanks in advance.
Thanks to you both. I tried both but in the end this is what worked for me
Cheers
You could just check for the presence of your remote directory:
The "problem" with your code is the management of the
errorlevel
to determine if the machine is or not online.The questions are: how does
ping
behave?, when iserrorlevel
set?If we are working with ipv6, the rules are
errorlevel
is set when there is no reply for all of the sent packets (all packets are lost)errorlevel
is not set if there is a reply to any of the sent packetsipv6 has a consistent behaviour and checking the errorlevel is a reliable way to know if the machine is online.
In ipv4 the rules are different
errorlevel
is set when there is no reply to at least one of the sent packetserrorlevel
is not set when there is a reply to all of the sent packets (no packet lost)But pinging an non available machine on the same subnet does no set the
errorlevel
, you get an "unreachable" answer, withn packets sent, n packed received, 0 packets lost
, all the packets get a reply from the same machine sending the packets.This behaviour in ipv4 when the machine is in the same subnet makes the errorlevel check fail.
How to solve the problem in ipv4?
The output of the
ping
command can be checked, if the stringTTL=
is present in the output, the target machine is online.For a "general" solution, this (adapted from a previous answer) can be used (seems a lot of code, but almost all are comments)