The question is different from How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?
since there will be some problems when passing arguments to a batch file which has the code of acquiring administrative privileges. After the privileges have been obtained, the arguments is lost and become undefined. I solve this problem by storing the arguments to a file first, please see detail in my answer.
Say the require batch file is run_as_admin.bat
,
By running run_as_admin.bat your_command your_params
we can execute the command with administrative privileges (e.g. run_as_admin delete /path/to/system_file
).
To run parameters as command,
run_params_as_cmd.bat
%* pause
To get administrative privileges, I find some code from http://larrynung.github.io/2014/01/01/batch-run-as-administrator/
Then I tried the following code
run_as_admin.bat
:@echo off call:TryToRunAsAdmin if %ERRORLEVEL%==1 exit /B echo got administrative privileges... :: run parameters as command <<< Here '%*' seems not be executed as a command. %* pause goto :eof :TryToRunAsAdmin set GetAdminScriptFile="%temp%\getadmin.vbs" REM --> Check for permissions >nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system" REM --> If error flag set, we do not have admin. if '%errorlevel%' NEQ '0' ( echo Requesting administrative privileges... call:UACPrompt set ERRORLEVEL=1 ) else ( if exist %GetAdminScriptFile% ( del %GetAdminScriptFile% ) set ERRORLEVEL=0 ) goto :eof :UACPrompt echo Set UAC = CreateObject^("Shell.Application"^) > %GetAdminScriptFile% echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> %GetAdminScriptFile% call %GetAdminScriptFile% goto :eof
To test that code, I tried some command which needs admin privileges
run_as_admin.bat reg add "HKLM\SOFTWARE\Classes\.php" /v PerceivedType /d text
run_as_admin.bat %SystemRoot%\system32\drivers\etc\hosts_old.txt
but these commands seem to be not executed but ignored as a string.
I guess the problem is related to the code, is there any other ways to write a batch file can run parameters as a command with administrative privileges?