Get current user on Windows

Example: I am registered as a user of TestUser. From this user, I am going to run the command line as administrator with the name AdminUser.

Is it possible to determine the name of the current input in TestUser from this command line?

I already have a scheduled task that always works as AdminUser, but in its action (batch file) I need to specify the name of the user who is currently logged in.

Any ideas?

+5
source share
3 answers

As far as I know, this is really impossible. Depending on how much you know about the user environment, there might be a workaround:

Command

qwinsta 

will provide you with a list of sessions for the computer. During these sessions, one of them will be active, so if this program is used in an interactive session, it will mainly contain a “registered user”, as you described it (this is much more complicated, maybe many users are logged in but only one can be active, and I just hope that you know enough about the use cases of your program to use this). You can analyze the output and work with this username.

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

In addition, I chose qwinsta.exe because it is a very simple approach that does not require API calls or anything else, I'm still not sure if CMD has sufficient parsing capabilities to get the necessary information for you.

+5
source

%username% variable contains .. well, username.

echo/%username%

EDIT

As you said, because you have a scheduled task, you can get the username from the 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% 

The %user% variable now contains the registered username.

+4
source

Here is a quick way to do this using a batch file:

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

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

0
source

Source: https://habr.com/ru/post/1211694/


All Articles