I am very new to batch but I need to write a script that can determine whether a certain user is logged into the server or not. To do this, I am using Query User
. Here is my code:
@echo off
set "account=<account name>"
set "output=C:\Login.txt"
query user %account% > temp.txt
findstr /i "%account%" temp.txt > nul
if %errorlevel% equ 0 (
findstr /i "Active" temp.txt > nul
if %errorlevel% equ 0 (
echo User %account% is logged in. > %output%
) else (
echo User %account% is not logged in. > %output%
)
) else (
echo User %account% not found. > %output%
)
del temp.txt
When I run this, it incorrectly tells me an account is logged in when I know it is not. To confirm this, I can run query user <user account>
, which gives me this output showing that the user is disconnected:
C:\>query user <user account>
USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
<account name> 34 Disc 2:24 8/2/2023 9:55 AM
What am I doing wrong?