8

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 5

13

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
  • Thanks. However powershell scripts are disabled by default on almost all machines. Right click->run as Admin on batch files would be more convenient in that case than first having users enable powershell scripts.
    – hazrmard
    Aug 13, 2016 at 1:25
  • 1
    @hazrmard This doesn't require script execution to be enabled, since you're just running a command, not a script file. (I just checked and -command can indeed be used even if scripts can't.)
    – Ben N
    Aug 13, 2016 at 1:27
  • True. But I am distributing a batch file among users. Which means I'll have to ask users to first type in this command in power shell to run the batch file. I don't even trust my users to Right click-> Run as admin. Hence my question in the first place :)
    – hazrmard
    Aug 13, 2016 at 1:30
  • 1
    @hazrmard You're not running a PowerShell command, you're invoking powershell.exe from your batch script to automatically run one PS command. The user will never even know PowerShell is involved.
    – Ben N
    Aug 13, 2016 at 1:31
  • Splendid. Works for cmd itself as well: powershell -command "Start-Process cmd.exe -Verb runas" Aug 14, 2018 at 10:14
1

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

1

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
1
  • it workded fine
    – lava
    Oct 7 at 11:59
0

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
-1

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

::::::::::::::::::::::::::::::::::::::::::::
:: Elevate.cmd - Version 4
:: Automatically check & get admin rights
:: see "https://stackoverflow.com/a/12264592/1016343" 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
1
  • dont run this code.it delete my entire code inside the folder
    – lava
    Oct 7 at 11:57

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.