How to run batch file command with elevated permissions?

I am writing a batch file that I will distribute among users. I need to run some commands with elevated permissions. My initial solution was to use:

runas /noprofile /user:Administrator SOME_COMMAND 

However many machines (including mine) have the hidden Administrator account inactive and so do not have an administrator password set up. I can also not specify another user name since different machines will have different users. Is there a way to replicate the "right click -> Run as Administrator" action via a batch file? I do not mind the prompt popping up, I just do not want the user to explicitly right-click and run as administrator.

4

5 Answers

You can take advantage of PowerShell, which is present on every modern Windows system.

Split the commands that need elevation off into a separate batch file, e.g. elevated.bat. Then, when it's time to run them, use this from your non-elevated script:

powershell -command "Start-Process elevated.bat -Verb runas"

The -Verb runas part is what causes the elevation prompt. If the original batch file is already running as admin, or if UAC prompts are off, the new file will be elevated without a prompt.

Note that the elevated batch processor's current directory will start out as System32. If that's a problem, you can use this alternate version to have it start in the same directory as the non-elevated script:

powershell -command "Start-Process cmd -ArgumentList '/c cd /d %CD% && elevated.bat' -Verb runas"

That causes the new cmd instance to first cd into the directory provided by the unelevated prompt's %CD% variable, then execute the desired batch file.

8

RunAdmin lets you run a program from command line with elevated rights (it will show the UAC so the user can enter credentials).

What I use is the following code:

::#################################################################################################################################
:: Elevate this script #
::#################################################################################################################################
( :: Check Admin rights and create VBS Script to elevate >nul fsutil dirty query %SYSTEMDRIVE% 2>&1 || ( :: Very little red console mode con cols=80 lines=3 color cf :: Message title Please wait... echo. echo Requesting elevated shell... :: Create VBS script echo Set UAC = CreateObject^("Shell.Application"^)>"%TEMP%\elevate.vbs" echo UAC.ShellExecute "%~f0", "%TEMP%\elevate.vbs", "", "runas", 1 >>"%TEMP%\elevate.vbs" if exist "%TEMP%\elevate.vbs" start /b /wait >nul cscript /nologo "%TEMP%\elevate.vbs" 2>&1 :: Delete elevation script if exist if exist "%TEMP%\elevate.vbs" >nul del /f "%TEMP%\elevate.vbs" 2>&1 exit /b )
)
pushd "%~dp0"
.... your code ....
popd

Put it after your @echo off and remarks.

2

Continuing on the answer by Ben N:

To make a batch script self-elevating (automatically restart as administrator if started unelevated) you can use the following code first in the script (here I am using FSUTIL DIRTY query to test for admin rights).

FSUTIL DIRTY query %SYSTEMDRIVE% >nul || ( PowerShell "Start-Process -FilePath '%0' -Verb RunAs" EXIT
)
REM Main code here

alternatively, if your script requires the working directory to be the same as the batch file location, use:

FSUTIL DIRTY query %SYSTEMDRIVE% >nul || ( PowerShell "Start-Process -FilePath cmd.exe -Args '/C CHDIR /D %CD% & "%0"' -Verb RunAs" EXIT
)
REM Main code here

Sorry for very bad english. This will be run batch file as elevated (with admin privileged) This script is created by Matt () And i modified the Matt script. Update: Added windows system folder checker. Script:

::::::::::::::::::::::::::::::::::::::::::::
:: Elevate.cmd - Version 4
:: Automatically check & get admin rights
:: see "" for description
:: Sorry for very bad english
:: Modified script. Added check windows
:: system folder and then add it to ENV
:: (Envronment Variable)
:::::::::::::::::::::::::::::::::::::::::::: @echo off CLS ECHO. ECHO ============================= ECHO Running Admin shell ECHO =============================
:init setlocal DisableDelayedExpansion set cmdInvoke=1
:checkWinSys set "ResultFile=%temp%\checkSysResult.txt" if exist "%SystemRoot%\Sysnative" ( echo 1 goto checkSysResult ) > "%ResultFile%" if exist "%SystemRoot%\System32" ( echo 2 goto checkSysResult ) > "%ResultFile%" setlocal EnableDelayedExpansion set count=0 for /f "tokens=*" %%x in (%ResultFile%) do ( set /a count+=1 set var[!count!]=%%x )
:checkSysResult if "%var[3]%"=="1" ( set winSysFolder=Sysnative & goto skip ) else ( set winSysFolder=System32 & goto skip )
:skip del "%ResultFile%" setlocal DisableDelayedExpansion
:init(1) set "batchPath=%~0" for %%k in (%0) do set batchName=%%~nk set "vbsGetPrivileges=OEgetPriv_%batchName%.vbs" setlocal EnableDelayedExpansion
:checkPrivileges NET FILE 1>NUL 2>NUL if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )
:getPrivileges if '%1'=='ELEV' (echo ELEV & shift /1 & goto gotPrivileges) ECHO. ECHO ************************************** ECHO Invoking UAC for Privilege Escalation ECHO ************************************** ECHO Set UAC = CreateObject^("Shell.Application"^) > "%vbsGetPrivileges%" ECHO args = "ELEV " >> "%vbsGetPrivileges%" ECHO For Each strArg in WScript.Arguments >> "%vbsGetPrivileges%" ECHO args = args ^& strArg ^& " " >> "%vbsGetPrivileges%" ECHO Next >> "%vbsGetPrivileges%" if '%cmdInvoke%'=='1' goto InvokeCmd ECHO UAC.ShellExecute "!batchPath!", args, "", "runas", 1 >> "%vbsGetPrivileges%" goto ExecElevation
:InvokeCmd ECHO args = "/c """ + "!batchPath!" + """ " + args >> "%vbsGetPrivileges%" ECHO UAC.ShellExecute "%SystemRoot%\%winSysFolder%\cmd.exe", args, "", "runas", 1 >> "%vbsGetPrivileges%"
:ExecElevation "%SystemRoot%\%winSysFolder%\WScript.exe" "%vbsGetPrivileges%" %* exit /B
:gotPrivileges setlocal & pushd . cd /d %~dp0 if '%1'=='ELEV' (del "%vbsGetPrivileges%" 1>nul 2>nul & shift /1) :::::::::::::::::::::::::::: ::START :::::::::::::::::::::::::::: REM Run shell as admin (example) - put here code as you like ECHO %batchName% Arguments: P1=%1 P2=%2 P3=%3 P4=%4 P5=%5 P6=%6 P7=%7 P8=%8 P9=%9 cmd /k

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like