Reference Iterating arrays in a batch file
I have the following:
for /f "tokens=1" %%Q in ('query termserver') do (
if not ERRORLEVEL (
echo Checking %%Q
for /f "tokens=1" %%U in ('query user %UserID% /server:%%Q') do (echo %%Q)
)
)
When running query termserver from the command line, the first two lines are:
Known
-------------------------
…followed by the list of terminal servers. However, I do not want to include these as part of the query user command. Also, there are about 4 servers I do not wish to include. When I supply UserID with this code, the program is promptly exiting. I know it has something to do with the if statement. Is this not possible to nest flow control inside the for-loop?
I had tried setting a variable to exactly the names of the servers I wanted to check, but the iteration would end on the first server:
set TermServers=Server1.Server2.Server3.Server7.Server8.Server10
for /f "tokens=2 delims=.=" %%Q in ('set TermServers') do (
echo Checking %%Q
for /f "tokens=1" %%U in ('query user %UserID% /server:%%Q') do (echo %%Q)
)
I would prefer this second example over the first if nothing else for cleanliness.
Any help regarding either of these issues would be greatly appreciated.
Again, there are multiple things to note here.
if errorlevelThe help for
ifsays:as syntax for the
if errorlevelcondition. That is, you must provide a number to compare against. Keep in mind thatif errorlevel nevaluates to true if the exit code was at least n.So
catches any error (that is signaled through the exit code), while
simply is always true.
Anyways, you probably want a
here, since that condition is true if no error occurred.
Skipping lines
The
for /fcommand has an argumentskip=nwhich can be used to skip lines at the start. If your output starts with two lines you don’t want, then you can just doIterating over multiple known values in
for /fThe problem with your second code snippet is that
foriterates line-wise. So when you give it a single environment variable it will tokenize it (and put the tokens into different variables), but the loop runs only once per line. Also note that usingsethere is a bit error-prone as you might get more back than you want. Something likewould have been easier. Still, that doesn’t solve the original problem. The easiest way to solve this would probably be something like the following:
(untested, but should work.)
ETA: Gah, and once again I miss the most obvious answer:
Note that this is simply
for, notfor /fand it will dutifully iterate over a list of values. I don’t know how I missed that one, sorry.