Search code examples
windowsbatch-filescripting

Determine which users are logged into a windows server


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?


Solution

  • Thank you to everyone for your help. I have combined some of the comments to create the following script. The purpose of this is to execute another batch file only if a certain user is logged out:

    @echo off
    setlocal
    
    set "account=<account name>"
    set "output=C:\Login.txt"
    
    %SystemRoot%\System32\query.exe user "%account%" 2>nul | %SystemRoot%\System32\findstr.exe /I /R /C:"%account% .* ACTIVE " >nul
    if errorlevel 1 (
        echo User %account% is not logged in.>"%output%"
        call another_script.bat
    ) else (
        echo User %account% is logged in.>"%output%"
    )
    
    endlocal