batch copy file on Ping Errorlevel=

February 26, 2009 at 09:37:18
Specs: Vista,2008, na
Hi, I have a simple script that copies a file to each computer contained in txt file.

I'm using the For /f to read the computer names, then I ping the computer and only if it's on the network do I try to copy the file.

The problem is the that the Ping cmd does not return the proper errorlevel when used in the For loop. When I used ping form cmd line it does return the proper ErrorLevel. I thought the problem was caused by the lack of the DelayedExpansion but using !ErrorLevel! instead of %EverLevel% does not work.

The script works but it ties to copy files even on computer that are not pingable, I've set Xcopy to ignore error but it takes the script a long time to run as it times out on the machine that are not reachable.

Any suggestions ?


Setlocal enabledelayedexpansion

FOR /F "tokens=1" %%a IN (mtl_computers.txt) do (
@echo Copying file to computer %%a
ping -1 n %%a >nul
if ERRORLEVEL 0 (xcopy custom.prf "\\%%a\c$\Program Files\Microsoft Office\custom.prf" /U /C /Y) else (echo do nothing)


See More: batch copy file on Ping Errorlevel=

Report •

February 26, 2009 at 11:57:30
You have a couple problems.

One is your usage.

If errorlevel 0

means 0 *OR MORE* so it will always resolve to TRUE and is therefore meaningless.

The other is a quirk of PING. It returms 1 only if it fails to resolve. Otherwise it returns 0 whether the IP is alive or fead.

@echo off & setLocal EnableDelayedExpansion

FOR /F "tokens=1" %%a IN (mtl_computers.txt) do (
ping -n 1 %%a | find "Reply" > nul
if not ERRORLEVEL 1 (
xcopy custom.prf "\\%%a\c$\Program Files\Microsoft Office\custom.prf" /U /C /Y
) else (
echo do nothing

If at first you don't succeed, you're about average.


Report •

February 26, 2009 at 13:22:25
Ok thank you M2,

My computer list came from AD so all of the account have valid DNS names, given that I changed the following :

ping -n 1 %%a | find "unreachable." > nul

As I did some test and realized that the "Reply" keyword was found on Ping request for both reachable and unreachable computers, but "unreachable" gave me the computers I wanted to skip.

One thing I don't understand When I looked for example of code I found some people using if %ErrorLevel%==1 and others if ERRORLEVEL 1 .
What's the difference between both ?

Report •

February 26, 2009 at 21:02:05
if %ErrorLevel%==1

mens EXACTLY 1


means 1 OR MORE

@echo off & setLocal EnableDelayedExpansion

find /v aaa

echo EL is %errorlevel%

find /v aaa

if ERRORLEVEL 1 echo 1 or more

find /v aaa

if %ErrorLevel%==1 echo exactly 1

If at first you don't succeed, you're about average.


Report •

Related Solutions

Ask Question