Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get currently logged on user on Windows

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?

like image 226
dEVIANT Avatar asked Jan 22 '15 11:01

dEVIANT


2 Answers

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.

like image 141
Syberdoor Avatar answered Sep 20 '22 23:09

Syberdoor


%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.

like image 36
Rafael Avatar answered Sep 19 '22 23:09

Rafael