Is it possible to automatically run a batch file as administrator
Yes, you're able to run a batch file with administrative rights. Unfortunately, you can't do this directly from the batch file it self. You would need to first create a shortcut of that batch file and change the properties for that shortcut in order to make this work.
To create a shortcut, there are many ways but the simplest and the fastest way is by using the Send to option in the context menu.
Right click batch file > Send to > Desktop (create shortcut)
Of course you can send the shortcut to where ever you would like. To elevate the batch file to run as admin, follow the steps below:
- Right-click the shortcut you just created (should be on the desktop or where ever you send it)
- Under the Shortcut tab, click the Advanced... button.
- Check the Run as administrator checkbox and press OK to both the modal window and the main properties window.
- Run the shortcut by double-clicking it and the batch file should run as administrator.
As posted in an answer by Ben Gripka to another question:
REM --add the following to the top of your bat file--
@echo off
:: BatchGotAdmin
:-------------------------------------
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...
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"=""
echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
:gotAdmin
pushd "%CD%"
CD /D "%~dp0"
:--------------------------------------
The accepted answer does indeed work. But I found that in Windows 7, I had to endure the UAC dialog each time the shortcut is clicked. This IMHO detracts significantly from the "automatically" in this question!
Then I found that in my own situation, the .bat
file in question is to be run by Task Scheduler. In this case, checking the Run with highest privileges
option on the General
tab of the task, nicely takes care of the problem. The .bat
is then run as administrator without any hassles.
PS: I didn't realize I couldn't upload images on this answer, 'cause I have a nice little screenshot sitting right with me now! Or can I?