Windows – How to get current logged in user name when running a batch file as administrator

batchpermissionswindowswindows 7

I have a batch file I can run to modify permissions to a folder in program files. It runs fine when the current user has local admin privileges, but for users who aren't I have to enter the domain administrator password for the changes to take place. When I double check the permissions setting on the folder, it shows the domain admin having full control over said folder.

How do I ensure that the current user logged in the windows gets full permission?

This is what I have as part of that batch file:

icacls "program files directory" /grant %userdomain%\%username%:F

Best Answer

How do I get current logged in user name when running a batch file as administrator

It runs fine when the current user has local admin privileges, but for users who aren't I have to enter the domain administrator password for the changes to take place.

With the below example you just set a variable with the environmental variables as you already have in your ICACLS command logic, and then use that variable to specify the account to grant the applicable permissions passing it to a CALL routine.

@ECHO OFF
SET Identity=%userdomain%\%username%
CALL :ICACLS "%Identity%"
GOTO EOF

:ICACLS
runas /user:MYDOMAIN\USER icacls "program files directory" /grant %~1:F
GOTO EOF

If you have trouble

If you're running cmd.exe with RUNAS and you determine the %userdomain%\%username% variables don't set (or list) the expected values which you need to use for the ICACLS commands to work as expected, then run the below commands in cmd.exe before using the RUNAS functionality to find the current logged on domain and username credential values which you can then use with the ICACLS commands for setting the permissions for that identity\security principal.

SET Identity=%userdomain%\%username%
ECHO %Identity%
Related Question