@echo off
:: Check if the script is running as Administrator
net session >nul 2>&1
if %errorLevel% neq 0 (
    echo This script requires Administrator privileges.
    pause
    exit /b
)

echo Current RDP user sessions:
query user | findstr /R "\<rdp-tcp#\>"

echo.
echo Disconnecting RDP users...

:: Get the list of all RDP sessions and disconnect each user except the Administrator
for /f "skip=1 tokens=1,2,3,4,5,6,7,*" %%a in ('query user ^| findstr /R "\<rdp-tcp#\>"') do (
    :: Skip the header line
    if /i not "%%a"=="Administrator" (
        :: Check if the state is Active or Inactive
        if /i "%%d"=="Active" (
            echo Disconnecting active user: %%a
            logoff %%c
        ) else if /i "%%d"=="Inactive" (
            echo Disconnecting inactive user: %%a
            logoff %%c
        )
    ) else (
        :: If the user is Administrator and the state is not Active or Inactive, skip
        if /i not "%%d"=="Active" if /i not "%%d"=="Inactive" (
            echo Skipping Administrator user as they are not in an active or inactive state.
        )
    )
)

echo.
echo All RDP users except the Administrator have been disconnected.

pause
exit /b