Is it possible to automatically run a batch file as administrator

50

24

I am wondering whether it is possible to automatically open a batch file as admin when you double-click on the batch file, because the commands need to be run with administrative rights.

Note: I already know about the solution of right-clicking on the file and clicking on Run As Administrator, but this is not an automatic solution.

Antp

Posted 2014-07-28T03:24:17.900

Reputation: 895

3

See also: How to request Administrator access inside a batch file

– ComFreek – 2014-07-28T14:53:15.797

I was able to get this to work for me: http://stackoverflow.com/a/13811519/27928

– Rohit – 2014-10-17T18:26:19.270

2how is two left clicks more automatic than one left- and one right click? – jiggunjer – 2016-01-17T12:44:33.193

Answers

45

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:

  1. Right-click the shortcut you just created (should be on the desktop or where ever you send it)
  2. Under the Shortcut tab, click the Advanced... button.
  3. Check the Run as administrator checkbox and press OK to both the modal window and the main properties window.
  4. Run the shortcut by double-clicking it and the batch file should run as administrator.

10100111001

Posted 2014-07-28T03:24:17.900

Reputation: 1 664

1You could always force the batch file to call the shortcut, and have the shortcut pass a parameter to know not to call the short cut. You would insert something like if "%~1" == "" start %USERPROFILE%\Desktop\Shortcut.lnk && GOTO :EOF right below @echo off, and make the shortcut link to program.bat a instead of just program.bat. – trlkly – 2014-07-28T05:20:27.273

2Ifedi writes "The accepted answer[this one from Tech1337] does indeed work. But I found that in Windows 7, I had to endure the UAC dialog each time the shortcut is clicked." <-- Though somebody else says it works without UAC – barlop – 2015-05-31T15:08:51.807

For me the shortcut doesn't run in the current directory when double clicked, though the .bat does. Even with the "Start in:" property on the shortcut filled out. So make sure your .bat specifies full file paths. – Rob Mosher – 2016-01-29T20:56:52.743

33

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"
:--------------------------------------

user399109

Posted 2014-07-28T03:24:17.900

Reputation: 331

Yes i found this and am using it currnetly. Thanks anyways! – Antp – 2014-12-18T04:20:11.453

Essentially what I was looking for. Was hoping there is a way to do this without using VB? – Chef Pharaoh – 2015-10-06T16:17:07.303

@ChefPharaoh this creates an elevated console to run the batch file. You can do the same with a powershell script. – jiggunjer – 2016-01-17T15:47:55.240

This was the best answer for me. – kasperhj – 2016-06-29T09:09:44.293

5

on Windows 7

  1. Create a shortcut to that Batch file

  2. Right-click the shortcut file

  3. Click advance button to find a checkbox for running as administrator

Check the screenshot below

Screenshot

fedmich

Posted 2014-07-28T03:24:17.900

Reputation: 269

1Your saying the same as the accepted answer. – Antp – 2015-02-11T09:53:21.640

Yes, I just wanted to create a simple list with screenshot for everyone that is in hurry. – fedmich – 2015-02-11T14:00:39.633

3If someone's in a hurry I doubt that they will scroll to the bottom for the answer.thanks anyway – Antp – 2015-02-11T21:14:36.783

Thank you worked for me on Windows 7. – Smeterlink – 2020-02-02T23:37:15.660

4

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?

Ifedi Okonkwo

Posted 2014-07-28T03:24:17.900

Reputation: 169

2If you add links to the images somebody will inline them for you. – Ramhound – 2014-10-07T18:50:18.203

@Ramhound. Add links to the images? The image is on my desktop, not somewhere online. Or, surely I'm missing something? – Ifedi Okonkwo – 2014-10-08T18:10:23.300

Yes; You upload them; You just can't inline the screenshots into your answer. – Ramhound – 2014-10-08T18:19:28.990

Either that upload button wasn't there, or I was half-blind yesterday! I'm sure it was the latter. Anyhow, I completed the file upload very nicely, only to be told I needed a rep of 10 to post images. Thanks, though. – Ifedi Okonkwo – 2014-10-08T18:27:04.573

You can still place the link in the answer though. – Ramhound – 2014-10-08T18:29:43.167

How then can I accomplish that? – Ifedi Okonkwo – 2014-10-08T19:55:52.907

Uh, well it works for me, i don't know what your going on about, maby your computer is stuffed? – Antp – 2014-11-17T07:43:09.300

@Antp. What are you referring to? What I said is: I could upload the screenshot, but at the end of it, it said I required a reputation of 10 and above to post images. When Ramhound said "You can still place the link in the answer though", I wondered how... – Ifedi Okonkwo – 2014-11-17T20:27:03.413

I ment to direct this comment to the answer. – Antp – 2014-11-17T22:38:26.277

@Antp. Okay...You mean the accepted answer works for your Windows 7 without the User Access Control dialog popping up each time? – Ifedi Okonkwo – 2014-11-18T07:30:49.497

Yep. Works for me. – Antp – 2014-11-20T01:02:28.073

I think he means he doesn't get more than the first prompt while running his scripts. But you should always get the first prompt, bypassing UAC is generally a bad idea. – jiggunjer – 2016-01-17T15:50:36.683

@IfediOkonkwo just use imgur.com – cascading-style – 2016-12-21T00:20:21.167

3

You can use my script Batch_Admin to automatically elevate the Administrator for use in any type of Batch own script, or BAT or .CMD. This function ensures the work on a standard environment, with standard tools and in the same way in different Windows systems. It uses several standard and built-in Windows commands. Do not use any other external scripts. It can be used to call any program as Administrator, not just scripts Batch. It suffices to create a small script, which then call the program that requires permission Administartor. Place this in any search PATH folder (from %PATH%).

To use it, you simply insert the following line (exactly as) in its parent Batch script, which is to be run as Administrator. This is best done at the top of our parent script and it is best that first, which will be called via the CALL further, some sub-scripts (see detailed explanation below).

net session >nul 2>nul&if errorlevel 1  Batch_Admin "%~0" %*

This can be inserted inside any child scripts, called by CALL syntax. To display a message while it is still does not have Administrator privileges, eg. for 5 seconds before calling Batch_Admin set the variable "ShowAdminInfo" on the number of seconds

SET ShowAdminInfo=5
net session >nul 2>nul&if errorlevel 1  Batch_Admin "%~0" %*

So how it works:

• Calls UAC.ShellExecute through VBScript to pick up user permissions

• Batch runs the script, or BAT or CMD

• Script caller can have a long name spaces included in the call in quotes

• Give back all the parameters call the master script passed from the command line, as if there was no transmission of the call and start something from scratch, also with special characters, like exclamation marks (!) and percentage (%), and also with parentheses ()

• Holds a master script location if the call took place in the directory where this script is the master

• Auxiliary displays a message if we set before ourselves the variable "ShowAdminInfo", eg. for 5 seconds which can prevent the immediate passage of the rights of the Administrator giving additional information and the possibility of an informed decision. Examples of setting that must be set: SET ShowAdminInfo=5 By default, because this variable is not defined, it does not display.

• The script is calling also in the system search path % PATH% and from network resource, such as: \Computer\share\test.bat

• Prevents misunderstandings in writing the necessary auxiliary files when the script calls several Batch_Admin almost at the same time. It uses the random number from 1 to 100

• But, the best is to use it on parent script. The transition to Administrator rights always requires that you run the script completely again, in a new window, in a new environment, without recourse to the the variables are set previously in our script and values of these variables did not pass then to call as Administrator. Just the script will be executed again.

Below a complete script Batch_Admin. Extended information about this is on my site.

Copy the following text into Notepad and save it to disk as: Batch_Admin.bat

@echo off
if "%~1"=="" (echo *** Batch_Admin ***&echo.&echo Automatically get admin rights for another Batch. See info inside.&TIMEOUT /T 30>nul&goto:eof)

::  A D M I N I S T R A T O R   - Automatically get admin rights for script batch. Paste this on top:    net session >nul 2>nul&if errorlevel 1  Batch_Admin "%~0" %*
::                                Also keep Batch directory localisation and then set variable:   PATH_BAT
::                                if earlier variable "ShowAdminInfo" is empty (not defined) then no info, else showing info with number of seconds
::
::                                Elaboration:  Artur Zgadzaj
setlocal
setlocal DisableDelayedExpansion

SET "Localy="
if exist "%~1"      SET "Localy=YES"
if exist "%~1.BAT"  SET "Localy=YES"
if exist "%~1.CMD"  SET "Localy=YES"
if defined Localy   FOR %%I IN ("%~1") DO SET "PATH_BAT=%%~dI%%~pI"

 SET P1=%~1
 SET Parameters=%*
 SET Parameters=%Parameters:!=^^!%
setlocal EnableDelayedExpansion
 SET Parameters=!Parameters:%P1%=!
 SET Parameters=!Parameters:%%=%%%%!
setlocal DisableDelayedExpansion
 SET Parameters=%Parameters:~3%

net session >nul 2>nul&if not errorlevel 1  goto Administrator_OK

if not defined ShowAdminInfo   goto skip_message_Administrator
echo.
echo Script:  %~1
echo.
echo *****************************************************************
echo ***    R U N N I N G     A S     A D M I N I S T R A T O R    ***
echo *****************************************************************
echo.
echo Call up just as the Administrator. You can make a shortcut to the script and set:
echo.
echo          shortcut ^> Advanced ^> Running as Administrator
echo.
echo     Alternatively run once "As Administrator"
echo     or in the Schedule tasks with highest privileges
echo.
echo Cancel Ctrl-C or wait for launch  %ShowAdminInfo%  seconds ...
TIMEOUT /T %ShowAdminInfo% > nul

:skip_message_Administrator
MD %TEMP% 2> nul
SET /A $Admin$=%RANDOM% * 100 / 32768 + 1

SET "Percent="
del "%TEMP%\$Admin_%$Admin$%_Test.bat" 2>nul
echo %Parameters% > "%TEMP%\$Admin_%$Admin$%_Test.bat"
if not exist "%TEMP%\$Admin_%$Admin$%_Test.bat"  SET Percent=^"
del "%TEMP%\$Admin_%$Admin$%_Test.bat" 2>nul

echo @SET "PATH_BAT=%PATH_BAT%"               > "%TEMP%\$Admin_%$Admin$%_Batch_Start.bat"
echo @SET "BatchFullName=%BatchFullName%"    >> "%TEMP%\$Admin_%$Admin$%_Batch_Start.bat"
if defined Localy  (echo @CD /D "%PATH_BAT%" >> "%TEMP%\$Admin_%$Admin$%_Batch_Start.bat")
echo @"%~1" %Parameters% %Percent% >> "%TEMP%\$Admin_%$Admin$%_Batch_Start.bat"

echo SET UAC = CreateObject^("Shell.Application"^)                                   > "%TEMP%\$Admin_%$Admin$%_Batch_getPrivileges.vbs"
echo UAC.ShellExecute "%TEMP%\$Admin_%$Admin$%_Batch_Start.bat", "", "", "runas", 1 >> "%TEMP%\$Admin_%$Admin$%_Batch_getPrivileges.vbs"
"%TEMP%\$Admin_%$Admin$%_Batch_getPrivileges.vbs"
endlocal
exit /B

:Administrator_OK
"%~1" %Parameters%
goto:eof
REM *** A D M I N I S T R A T O R  - Automatically get admin rights  (The End)  ***

Artur Zgadzaj

Posted 2014-07-28T03:24:17.900

Reputation: 31

I think this is similar or identical to the above answer: http://superuser.com/a/852877/375935

– jiggunjer – 2016-01-17T15:52:06.180

1

@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"  
    echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"  
    "%temp%\getadmin.vbs"  
    exit /B
:gotAdmin  
chkdsk

This also works SOURCE: https://social.technet.microsoft.com/Forums/windows/en-US/bc8a4561-d97e-4339-9b1c-9b90e54a7f92/request-elevation-inside-cmdbatch-file

Josue Moreno Cervantes

Posted 2014-07-28T03:24:17.900

Reputation: 11

Can you explain your solution? – scai – 2015-11-26T08:08:05.157

1

Another version of http://superuser.com/a/852877/375935

– jiggunjer – 2016-01-17T15:54:05.123

1

Alternatively you could create a second batch file, this could allow you to run anything as an administrator, while only entering the administrator password once. The password is saved in an authentication token, and takes some real computer know how to crack.

runas /savecred /user:(domain)\(admin user) "(file path to exe,bat,whatever)"

Brapapple

Posted 2014-07-28T03:24:17.900

Reputation: 19

0

It is an example to run the bat as administrator. It works for me.

It goes like this:

if "%~s0"=="%~s1" ( cd %~sp1 & shift ) else (
  echo CreateObject^("Shell.Application"^).ShellExecute "%~s0","%~0 %*","","runas",1 >"%tmp%%~n0.vbs" & "%tmp%%~n0.vbs" & del /q "%tmp%%~n0.vbs" & goto :eof
)
:eof
start Cmd /k "netsh wlan show profile"
pause </

cls
Color 0A
@echo off
echo.
cls
set/p ProfileName=Type the name of the current Wifi signal? 
echo.
start Cmd /k "netsh wlan show profile name=%ProfileName% key=clear"
pause </
exit
pause

JoshMoreNo

Posted 2014-07-28T03:24:17.900

Reputation: 11

Welcome to Super User! While this may answer the question, it would be a better answer if you could provide some explanation why it does so. – DavidPostill – 2015-11-25T21:21:24.220

Yet another variant of http://superuser.com/a/852877/375935

– jiggunjer – 2016-01-17T15:55:05.060

0

You can use a command line utility elevate. (download link - https://drive.google.com/open?id=0Bz7qe_olclTwVGZLUklFMHNxQ00 )

Usage: Elevate [-?|-wait|-k] prog [args]
-?    - Shows this help
-wait - Waits until prog terminates
-k    - Starts the the %COMSPEC% environment variable value and
                executes prog in it (CMD.EXE, 4NT.EXE, etc.)
prog  - The program to execute
args  - Optional command line arguments to prog

T.Todua

Posted 2014-07-28T03:24:17.900

Reputation: 2 436

Doesn't this bring up a UAC panal? – Antp – 2015-11-11T20:46:16.317

that brings up... however, it's better, than nothing ( seeing "access denied" ..) – T.Todua – 2015-11-17T13:41:23.893

Not really "automatic" though, is it – Antp – 2015-11-17T20:20:08.233