@echo off setlocal enabledelayedexpansion :: Output filename set "output_file=allowed_pcs.csv" echo [INFO] Extracting session information... :: 1. Get the Computer Name set "pc_name=%COMPUTERNAME%" :: 2. Get the current Username and Session ID :: Using 'query user' for more stable output parsing compared to qwinsta set "found=false" for /f "skip=1 tokens=1,2,3" %%i in ('query user %USERNAME%') do ( :: %%i = Username, %%j = SessionName or ID, %%k = ID or State :: Check if the 2nd column is a number (Session ID) echo %%j | findstr /r "^[0-9][0-9]*$" >nul if not errorlevel 1 ( set "user_name=%%i" set "session_id=%%j" ) else ( :: If 2nd column is SessionName (e.g., console), ID is in the 3rd column set "user_name=%%i" set "session_id=%%k" ) :: Remove the ">" prefix from the username if present set "user_name=!user_name:>=!" set "found=true" ) if "%found%"=="false" ( echo [ERROR] Could not identify active session. pause exit /b ) :: 3. Prompt user for a description set /p desc="Enter a description for this PC (e.g. Sales-Desktop): " :: 4. Output to CSV in append mode :: Wrapping in parentheses to prevent accidental file redirection issues (echo %pc_name%,%user_name%,%session_id%,%desc%)>> "%output_file%" echo. echo [SUCCESS] Information added to %output_file% echo Data: %pc_name%,%user_name%,%session_id%,%desc% echo. pause