0

I would like to know which user is logged in to Windows from the bat script I launch with right click and "Run as Administrator". If I try echo %username% the script obviously output "Administrator"

Is there a way to know which user launched a cmd command as administrator?

How to reproduce:

  1. Log in to Windows with a normal user (in my case "test_user")
  2. Launch a .bat as administrator (right click and choose "run as administrator")

If in the .bat file there is the environment variables %username% it is going to be translated in "Administrator" instead of "test_user"

How can I know which user launched the .bat file as "administrator"?

2 Answers 2

0

If you make your own user an administrator, and you right-click run as admin, and then provide your user's credential, then %username% will contain the correct user.

If that is really not possible, then you can use the command quser to query active users and see which session is active. This will not work correctly on a terminal server, but on a local computer, it should show you just one user.

The downside is that you can't really get the username this way if you limit yourself to just batch scripting. With powershell, maybe...

0

Use the command query user.

It will show all user sessions with their user names, like this :

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .