Have you ever used a nested 'for /f' command and realised that it's skipping some of your items because the operation you are executing against each item is not matching your primary criteria?
For example, if you have a control file listing computer names, and you want to report the IP address if the machine responds to a ping:
for /f %i in (test.txt) do for /f "tokens=1" %m in ('"ping -n 1 %i find /i "reply""') do @echo %i,%m
For a machine that either can't be resolved or doesn't reply, that machine would be skipped from the output.
However inside the second for loop, you can check the errorlevel returned by the find command, and echo an alternate response:
for /f %i in (test.txt) do @for /f "tokens=3 delims=: " %m in ('"ping -n 1 %i find /i "reply" & if errorlevel 1 echo 1 2 NoReply"') do @echo %i,%m
Note that the nested 'for /f' command above is extracting the third token, so the errorlevel echo also requires three tokens…
This provides a catchall so that for each of your items, something will be echoed, useful in many situations when you're potentially trying to check dozens or hundreds of items for something and you want results for all items.
Wayne's World of IT (WWoIT), Copyright 2008 Wayne Martin.
Information regarding Windows Infrastructure, centred mostly around commandline automation and other useful bits of information.
No comments:
Post a Comment