55

I need to run a batch file which needs to register a DLL. The DLL registration is failing because the Batch file is not starting the command prompt as "administrator".

Is there any way to start the "Command Prompt" as administrator through the batch file.

Environment: Win7/Vista

Colin Brock
  • 21,267
  • 9
  • 46
  • 61
JChan
  • 1,411
  • 4
  • 24
  • 34
  • 1
    http://technet.microsoft.com/en-us/library/bb490994 – Marc B Jul 17 '12 at 14:44
  • See also [How can I auto-elevate my batch file, so that it requests from UAC admin rights if required?](http://stackoverflow.com/questions/7044985/how-can-i-auto-elevate-my-batch-file-so-that-it-requests-from-uac-admin-rights) – GAThrawn May 13 '13 at 14:50
  • @EdGreaves is that link not to this question? – achAmháin Oct 20 '17 at 09:46
  • See also: https://stackoverflow.com/questions/6811372/how-to-code-a-bat-file-to-always-run-as-admin-mode/13811519 – Ed Greaves Nov 29 '17 at 15:28
  • The question is ambiguous: is the question to run it as the user Administrator, or to run it with administrative rights? – undrline - Reinstate Monica Oct 26 '18 at 18:59
  • Possible duplicate of [How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?](https://stackoverflow.com/questions/7044985/how-can-i-auto-elevate-my-batch-file-so-that-it-requests-from-uac-administrator) – Matt Jan 14 '19 at 09:51

12 Answers12

58

This script does the trick! Just paste it into the top of your bat file. If you want to review the output of your script, add a "pause" command at the bottom of your batch file.

This script is now slightly edited to support command line args.

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

::ENTER YOUR CODE BELOW:
Edudjr
  • 1,676
  • 18
  • 28
Lokesh Kumar
  • 801
  • 2
  • 8
  • 13
  • this code is working for enabling windows update service. But not working for disabling windows update service `sc stop wuauserv & sc config wuauserv start= disabled` – proseosoc Jan 02 '17 at 18:24
  • 1
    Note: this code will occasionally not function if run from sub-directories of a different drive. See my question on it here: https://superuser.com/questions/1192426/batch-file-only-runs-properly-from-c-drive/1192427#1192427 – Blaine Mar 26 '17 at 02:58
  • 1
    OMG - this worked perfectly! I'm of an age where everything was batch files and DOS programming, and know most tricks but didn't realise this was possible! I'm highly impressed! Thanks for sharing! – Scott Jun 19 '19 at 08:29
  • Calling the script with args: %* is set before the code but empty after the last line – Joe Jun 05 '23 at 08:34
16

You might have to use another batch file first to launch the second with admin rights.

In the first use

runas /noprofile /user:mymachine\administrator yourbatchfile.bat

Upon further reading, you must be able to type in the password at the prompt. You cannot pipe the password as this feature was locked down for security reasons.

You may have more luck with psexec.

Bali C
  • 30,582
  • 35
  • 123
  • 152
9

Press Ctrl+Shift and double-click a shortcut to run as an elevated process.

Works from the start menu as well.

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
caractacus
  • 115
  • 1
  • 1
7

(This is based on @DarkXphenomenon's answer, which unfortunately had some problems.)

You need to enclose your code within this wrapper:

if _%1_==_payload_  goto :payload

:getadmin
    echo %~nx0: elevating self
    set vbs=%temp%\getadmin.vbs
    echo Set UAC = CreateObject^("Shell.Application"^)                >> "%vbs%"
    echo UAC.ShellExecute "%~s0", "payload %~sdp0 %*", "", "runas", 1 >> "%vbs%"
    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
goto :eof

:payload
    echo %~nx0: running payload with parameters:
    echo %*
    echo ---------------------------------------------------
    cd /d %2
    shift
    shift
    rem put your code here
    rem e.g.: perl myscript.pl %1 %2 %3 %4 %5 %6 %7 %8 %9
goto :eof

This makes batch file run itself as elevated user. It adds two parameters to the privileged code:

  • word payload, to indicate this is payload call, i.e. already elevated. Otherwise it would just open new processes over and over.

  • directory path where the main script was called. Due to the fact that Windows always starts elevated cmd.exe in "%windir%\system32", there's no easy way of knowing what the original path was (and retaining ability to copy your script around without touching code)

Note: Unfortunately, for some reason shift does not work for %*, so if you need to pass actual arguments on, you will have to resort to the ugly notation I used in the example (%1 %2 %3 %4 %5 %6 %7 %8 %9), which also brings in the limit of maximum of 9 arguments

Community
  • 1
  • 1
Alois Mahdal
  • 10,763
  • 7
  • 51
  • 69
7

To prevent the script from failing when the script file resides on a non system drive (c:) and in a directory with spaces.

Batch_Script_Run_As_Admin.cmd

@echo off
if _%1_==_payload_  goto :payload

:getadmin
    echo %~nx0: elevating self
    set vbs=%temp%\getadmin.vbs
    echo Set UAC = CreateObject^("Shell.Application"^)                >> "%vbs%"
    echo UAC.ShellExecute "%~s0", "payload %~sdp0 %*", "", "runas", 1 >> "%vbs%"
    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
goto :eof

:payload

::ENTER YOUR CODE BELOW::   





::END OF YOUR CODE::

echo.
echo...Script Complete....
echo.

pause
Northstrider
  • 1,149
  • 13
  • 14
  • This code seems to be working, but I always need to confirm. Is there any way to auto-confirm without user interaction? cheers! – vlatko606 Dec 22 '22 at 10:38
  • I'm calling the batch from vba but for some reason when I add this the code thinks the execution was finish and it keep going. How Can I wait until the execution finish – Daniel Hernandez Feb 15 '23 at 19:13
6

You can use a shortcut that links to the batch file. Just go into properties for the shortcut and select advanced, then "run as administrator".

Then just make the batch file hidden, and run the shortcut.

This way, you can even set your own icon for the shortcut.

jojois74
  • 795
  • 5
  • 10
  • 1
    My `run as administrator` checkbox is disabled. How can I get over it? – Nam G VU Feb 24 '14 at 11:51
  • Hm, not sure. That's interesting. – jojois74 Feb 06 '18 at 08:48
  • @NamGVU https://superuser.com/questions/880290/run-as-administrator-greyed-out-on-shortcut – ntrch Jan 22 '19 at 15:13
  • @NamGVU You can download already created portable (generated in the `Windows XP`) shortcuts set from here: https://sourceforge.net/p/contools/contools/HEAD/tree/trunk/Scripts/Tools/ToolAdaptors/lnk/ Or even generate your own: https://sourceforge.net/p/contools/contools/HEAD/tree/trunk/Scripts/Tools/ToolAdaptors/vbs/ – Andry Jan 08 '21 at 01:36
5

This Works for me in Windows 7 to 10 with parameters, when kick starting app or file from anywhere (including browser) and also when accessing file from anywhere. Replace (YOUR BATCH SCRIPT HERE anchor) with your code. This solution May Help :)

@echo off

call :isAdmin

if %errorlevel% == 0 (
    goto :run
) else (
    echo Requesting administrative privileges...
    goto :UACPrompt
)

exit /b

:isAdmin
    fsutil dirty query %systemdrive% >nul
exit /b

:run
  <YOUR BATCH SCRIPT HERE>
exit /b

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    echo UAC.ShellExecute "cmd.exe", "/c %~s0 %~1", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
exit /B
GChuf
  • 1,135
  • 1
  • 17
  • 28
2

Maybe something 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
)
dev5er6
  • 119
  • 1
  • 2
1

As user2549366 suggested before, "You can use a shortcut that links to the batch file." but in the Properties->Compatibility tab of the shortcut, run as administrator may be disabled.

So instead You just right click on your "file.bat - shortcut" then go to ->Properties->Shortcut tab -> Advanced and there you can click Run as administrator. After that, You can execute the shortcut.

bajla
  • 163
  • 2
  • 2
  • 12
1

You can use the under codes to run a CMD as administrator via a batch file.

@echo off
powershell -Command "Start-Process cmd -Verb RunAs -ArgumentList '/k cd /d %~dp0'"
exit 

This code uses PowerShell to start a new Command Prompt process with administrative privileges. The -Verb RunAs parameter tells PowerShell to run the process as an administrator, and the /k cd /d %~dp0 argument changes the directory to the location of the batch file But, I used it for windows 10.

Mohebbikhah
  • 53
  • 1
  • 9
-2

Here's a more simple version of essentially the same file.

@echo off
break off
title C:\Windows\system32\cmd.exe
cls

:cmd
set /p cmd=C:\Enter Command:

%cmd%
echo.
goto cmd
Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
gaws
  • 5
  • 1
-5

Make a text using notepad or any text editor of you choice. Open notepad, write this short command "cmd.exe" without the quote aand save it as cmd.bat.

Click cmd.bat and choose "run as administrator".

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
pango
  • 9