Get currently logged on user on Windows

19,194

Solution 1

As far as I know this is not really possible. Depending on how much you know about the environment of the users, the following might be a workaround however:

The command

qwinsta

will give you a list of sessions for the computer. Within these sessions one will be the active one, so if this program is used in an interactive session only this will basically contain the "logged in user" as you described it (it is far more complicated really, there could be many users logged on but only one can be active and I just hope you know enough about the usage scenario of your program to make use of that). You could parse the output and work with that username.

Of course this is a dirty hack and it assumes that during the run time of your task there is no chance that users change.

Also though I chose the qwinsta.exe because it is a very basic approach that needs no API calls or something I am still not sure if the CMD has sufficient parsing capabilities to get the necessary information for you.

Solution 2

%username% variable contains.. well, the user name.

echo/%username%

EDIT

As you said, because you are in a scheduled task, you can get the user name from Windows Registry

@echo off
for /f "tokens=3" %%a in ('reg query HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\SessionData\1 /v LoggedOnUserName') do (
set "user=%%a")
set "user=%user:.\=%"
echo/%user%

Now %user% variable contains the logged user name.

Solution 3

Here is a quick way to make this happen using a batch file would be this command:

for /F "tokens=1,2" %%i in ('qwinsta /server:%COMPUTERNAME% ^| findstr "console"') do set tempVar=%%j

echo %tempVar% will show whatever user is actually logged in. Not the user who launched the batch file.

Share:
19,194
dEVIANT
Author by

dEVIANT

Updated on June 22, 2022

Comments

  • dEVIANT
    dEVIANT almost 2 years

    Example: I am logged in as user TestUser. From this user I am going to run a command line as an administrator named AdminUser.

    Is it possible from this command line to determine the name of the currently logged in TestUser?

    I already have scheduled task which is always running as AdminUser, but in its action (batch file), I need to name of the currently logged in user.

    Any ideas?