I have read several posts regarding my issue (e.g. this one) but still cannot get the following running:
for /f "tokens=*" %%U in ('query user * /server:MYSERVER') do (
if %%U contains %USERNAME% then do something.
)
So the issue is that the string to be searched for is not hard coded but a variable. I have tried all variants of %% and !! but always failed. Is there the one variant I missed to try?
Edit:
This does not answer the actual question (so it remains open) but it solves the specific task in a different way. In case it´s useful for someone I post it here (rather than in a comment because there you cannot add line breaks).
for /F "tokens=1 delims=" %%U in ('query user * /server:MYSERVER') do (
for /F "tokens=1 delims= " %%V in ("%%U") do (
if /I "%%V" == "%USERNAME%" (
echo You: %%U
) ELSE (
echo %%U
)
)
)
It is based on Mofi´s suggestion below. However, I don´t have any > characters in my output of the query command. For that reason I have used a simple space as delimiter. I only wonder why it works with token 1 because the output seems to start with a space, thus a delimiter (if it´s not #160 in reality).
The only bad thing on that is that it does not seem to be possible to add the 2>NUL to the command:
for /F "tokens=1 delims=" %%U in ('query user * /server:MYSERVER 2>NUL') do (
...
Then the batch file drops an error. That is a pity because this way you could prevent the (stderr) message if no user is logged on at all.