There are many ways to get the current logged on user. This one is does not rely on any third party tools. It has some things that I like to uses but do not see frequently. You will see the setlocal command, which limits the environment change to the batch file. I have prompted input for a environment variable. The FOR command parses the output of the WMIC command, which is WMI command line, native to XP and later systems. Without DSQuery, you only get the NT Name. If you are an admin interested in scripting, then DSQuery should be on your workstation. It is part of the Windows Server 2003 Administration Tools Pack.
The output of the batch file looks like this:
Get logged on user for what computer name?: somecomputername
Pinging somecomputername
somecomputername responds to ping
UsersNTName is logged onto somecomputername
displayname
TheirLast, TheirFirst
Done.
REM ===== LoggedOnUser.cmd ====
@echo off
:: Gets logged on username and display name
:: relies on WMIC, native to XP and later and
:: dsquery, part of admintools for 2003
:: alan dot kaplan at va dot gov
:: DATE : 5/5/2009
setlocal
set PCName=%1
if %1z == z set /p PCName=Get logged on user for what computer name?: &goto Test
cls
:test
echo Pinging %PCName%
ping -n 1 -l 1 %PCName% | find “Reply” > nul
if errorlevel 1 goto offline
if errorlevel 0 goto main
goto end
:offline
echo %PCName% does not respond to ping!
goto end
:main
echo %PCName% responds to ping
Echo.
rem For command to get SamAccountName
rem delims are \ and space
REM wmic relies on functioning WMI
rem all one line
for /f “tokens=1-3 delims=\ ” %%i in (‘wmic /node:”%PCName%” computersystem get username’) do set FoundUser=%%j
rem extended if syntax
if “%FoundUser%z” == “z” (
echo No User logged on
pause
goto end
) ELSE (
echo %FoundUser% is logged onto %PCName%
rem or DSQUERY USER -samid %PCName% | DSGET USER -display
rem this gives a little nicer display of results, you can rem it out if you don’t have dsquery installed
rem all one line
dsquery * domainroot -filter “(&(objectCategory=Person)(objectClass=User)(sAMAccountName=%FoundUser%))” -attr displayname
)
Echo Done.
pause
:end
endlocal