%Errorlevel% in for

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
 
P

Phil Robyn

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.
 
W

Wensi Peng

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top