Windows Batch – Get name of currently logged-in user

batchfindstrwindows

In a sort of small mitigation for a large network for the exploit of replacing utilman.exe on windows repair, by cmd.exe, then changing user password, I'm doing a small script based on EventSentry tool that will detect that utilman.exe is changed and I can attach an action to it.
But this detect will take place after the attacker already logged in to the local computer.
So, I'm doing a script that will change access rights, and blocking delete and rename of utilman.exe and I want to add the password change for the current logged user and then log off.

This is what I have so far:

 @ECHO off
 takeown /f c:\windows\system32\utilman.exe
 icacls c:\windows\system32\utilman.exe /deny *S-1-1-0:(DE,WD,AD,RX)
 net user [NeedToGetLogedUser] 123456
 shutdown -L

The action that I attach will execute this script under another user (not the actual logged user). So I need to get the actual current user logged to the computer instead of the user that this script will run under.

I was thinking of:

C:\Users\MyUser>query user
USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME
>MyUser              console             1  Active      none   7/9/2020 6:27 PM

But I can't figure out how to parse the result just to get "MyUser" alone (using findstr) to use it with the net user command.

Best Answer

for /F "tokens=2 delims==" %f in ('wmic computersystem get username /value ^| find "="') do set "ConsoleUser=%f"

Output:

" \>set "ConsoleUser=COMPUTERORDOMAINNAME\username

When run in a batch file, replace % with %%

for /F "tokens=2 delims==" %%f in ('wmic computersystem get username /value ^| find "="') do set "ConsoleUser=%%f"
echo %ConsoleUser%