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%