%Errorlevel% in for

  • Thread starter Thread starter Wensi Peng
  • Start date Start date
W

Wensi Peng

Hello,

I try to use %errorlevel% to control a batch program. When I use it in FOR
loop it does NOT give right error number after ping. I expect 0 with reply
from and 1 with request time out.
If ping runs out of FOR loop it gives correct expected error number.

Thanks for your help

Wensi

My example:
@echo off
ping -n 1 NotExistingServer
echo errorlevel %ErrorLevel%

for /f "tokens=1* delims=" %%i in (Servers.txt) do (
ping -n 1 %%i
echo errorlevel %ErrorLevel%
pause
)

server.txt
NotExistingServer
Server1
 
Wensi said:
Hello,

I try to use %errorlevel% to control a batch program. When I use it in FOR
loop it does NOT give right error number after ping. I expect 0 with reply
from and 1 with request time out.
If ping runs out of FOR loop it gives correct expected error number.

Thanks for your help

Wensi

My example:
@echo off
ping -n 1 NotExistingServer
echo errorlevel %ErrorLevel%

for /f "tokens=1* delims=" %%i in (Servers.txt) do (
ping -n 1 %%i
echo errorlevel %ErrorLevel%
pause
)

server.txt
NotExistingServer
Server1
When CMD.EXE executes your 'for /f ... do ( ... )',
it resolves any environment variables within the parentheses
once *prior* to execution. So you should use delayed variable
expansion and change '%errorlevel%' to '!errorlevel!'.

If you type 'SET /?' (without the apostrophes) at the CMD prompt,
you can read all about this.
 
Thank you! it works
Phil Robyn said:
When CMD.EXE executes your 'for /f ... do ( ... )',
it resolves any environment variables within the parentheses
once *prior* to execution. So you should use delayed variable
expansion and change '%errorlevel%' to '!errorlevel!'.

If you type 'SET /?' (without the apostrophes) at the CMD prompt,
you can read all about this.

--
Phil Robyn
Univ. of California, Berkeley

u n z i p m y a d d r e s s t o s e n d e - m a i l
 
Back
Top