Batch Script to Run as Administrator


Batch Script to Run as Administrator



I'm writing a client/server checking program but it needs to run as Administrator.



I want this to run silently on my network and users, and I don't want the "Run as" Administrator" prompt. Is there any beginning code that I can place into the batch file to make it auto-run as Administrator?




11 Answers
11



No: The - create a shortcut [ -> Compatibility -> "run this program as an administrator" ] solution does not work.



This option is greyed out in Windows 7. Even with UAC disabled



No: The runas /env /user:domainAdministrator <program.exe/command you want to execute> is also not sufficient because it will prompt the user for the admin password.


runas /env /user:domainAdministrator <program.exe/command you want to execute>



Yes: Disable UAC -> Create a job using task scheduler, this worked for me.



You can let the script enable UAC afterwards by editing the registry if you would want. In my case this script is ran only once by creation of a windows virtual machine, where UAC is disabled in the image.



Still looking forward for the best approach for a script run as admin without too much hassle.





UAC part Disable UAC C:WindowsSystem32cmd.exe /k %windir%System32reg.exe ADD HKLMSOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem /v EnableLUA /t REG_DWORD /d 0 /f Enable UAC C:WindowsSystem32cmd.exe /k %windir%System32reg.exe ADD HKLMSOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem /v EnableLUA /t REG_DWORD /d 1 /f
– zenin
Jan 8 '14 at 14:59


@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`





This perfectly works for me. Thanks.
– Emad
Sep 18 '17 at 9:04



its possible using syntax:


RUNAS [/profile] [/env] [/netonly] /user:user Program

Key :
/profile Option to load the user's profile (registry)
/env Use current environment instead of user's.
/netonly Use the credentials specified only for remote connections.
/user Username in form USER@DOMAIN or DOMAINUSER
(USER@DOMAIN is not compatible with /netonly)
Program The command to execute



example :


runas /env /user:domainAdministrator <program.exe/command you want to execute>





This will prompt for a password, which he does not want.
– eddyq
Jul 22 '14 at 1:33





@eddyq True, however this answers the title of the question, even if the body of the question alters what he said he wants.
– leetNightshade
Feb 10 '15 at 4:10






The title is not the question. The body text is the question. The title is the title. The body takes priority, because it contains the details.
– Ken White
Jan 18 at 17:35



You have a couple options.



If you need to do it using only a batch file and native commands, check out How can I auto-elevate my batch file, so that it requests from UAC admin rights if required?.



If 3rd-party utilities are an option, you can use a tool like Elevate. It is an executable that you call with the program you want to run elevated as a parameter.
Like this:
elevate net share ....


elevate net share ...



Following is a work-around:



Running the shortcut will execute your batch script as administrator.



I made this slight modification to Matt's script to enable it to run from within a single script (just add this to the beginning of any script requiring UAC invocation), but read below the code for an even better solution that I've found on a blog:


:: ### START UAC SCRIPT ###

if "%2"=="firstrun" exit
cmd /c "%0" null firstrun

if "%1"=="skipuac" goto skipuacstart

:checkPrivileges
NET FILE 1>NUL 2>NUL
if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )

:getPrivileges
if '%1'=='ELEV' (shift & goto gotPrivileges)

setlocal DisableDelayedExpansion
set "batchPath=%~0"
setlocal EnableDelayedExpansion
ECHO Set UAC = CreateObject^("Shell.Application"^) > "%temp%OEgetPrivileges.vbs"
ECHO UAC.ShellExecute "!batchPath!", "ELEV", "", "runas", 1 >> "%temp%OEgetPrivileges.vbs"
"%temp%OEgetPrivileges.vbs"
exit /B

:gotPrivileges

setlocal & pushd .

cd /d %~dp0
cmd /c "%0" skipuac firstrun
cd /d %~dp0

:skipuacstart

if "%2"=="firstrun" exit

:: ### END UAC SCRIPT ###

:: ### START OF YOUR OWN BATCH SCRIPT BELOW THIS LINE ###



My modification uses two file arguments as you can see, which isn't particularly elegant but does the job (and you can always hide them away at the tail end by reserving the first few arguments using dummy placeholders). Additionally, AFAIK Matt's script doesn't support spaces in file paths and this limitation also applies to my modification of this script.



This issue seems to be inherent in the way VBS handles these paths but on the below link there's an even better VBS-based solution for invoking UAC that runs from within a single script without the need for a workaround like this using file arguments and that also supports spaces in file paths:



http://pcloadletter.co.uk/2012/12/11/uac-elevation-for-batch-script/



The script on this link makes slightly different VBS calls as you'll notice, which for some reason circumvents the issue with spaces.



Create a shortcut and set the shortcut to always run as administrator.



How-To Geek forum Make a batch file to run cmd as administrator solution:



Make a batch file in an editor and nameit.bat then create a shortcut to it. Nameit.bat - shortcut. then right click on Nameit.bat - shortcut ->Properties->Shortcut tab -> Advanced and click Run as administrator. Execute it from the shortcut.





You can't set 'Run as Administrator' on a batch file or a shortcut pointing to it, annoyingly.
– StormPooper
Jul 22 '14 at 13:04





You can't set it on the batch file - but you can set it on a shortcut pointing to it
– icc97
Apr 20 '15 at 13:31



As I have not found any simple script so far, here's my two cents:


set ELEVATE_APP=Full command line without parameters for the app to run
set ELEVATE_PARMS=The actual parameters for the app
echo Set objShell = CreateObject("Shell.Application") >elevatedapp.vbs
echo Set objWshShell = WScript.CreateObject("WScript.Shell") >>elevatedapp.vbs
echo Set objWshProcessEnv = objWshShell.Environment("PROCESS") >>elevatedapp.vbs
echo objShell.ShellExecute "%ELEVATE_APP%", "%ELEVATE_PARMS%", "", "runas" >>elevatedapp.vbs
DEL elevatedapp.vbs



You could put it as a startup item... Startup items don't show off a prompt to run as an administrator at all.



Check this article Elevated Program Shortcut Without UAC rompt





Answers on Stack Overflow shouldn't contain "Google to find the answer".
– Shadow Wizard
May 12 '13 at 20:12





Sorry my bad. Editing
– sandrows
May 13 '13 at 12:14





Better now, thanks.
– Shadow Wizard
May 13 '13 at 12:21



If all above answers is not to your liking you can use autoIT to run your file (or what ever file) as a specific user with their credentials.



Sample of a script that will run a program using that users privelages.


installAdmin()

Func installAdmin()
; Change the username and password to the appropriate values for your system.
Local $sUserName = "xxxxx"
Local $sPassword = "xxx"
Local $sDirectory = "C:ASD4VMDownload"
Local $sFiletoRun = "Inst_with_Privileges.bat"

RunAsWait($sUserName, @ComputerName, $sPassword, 0, $sDirectory & $sFiletoRun)
EndFunc ;==>Example



AutoIT can be found here. -> It uses a .ua3 format that is compiled to a .exe file that can be run.



Don't waste your time, use this one line command:


echo createobject("shell.application").shellexecute "cmd",,,"runas",1 > runas.vbs & start /wait runas.vbs & del /f runas.vbs




Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).


Would you like to answer one of these unanswered questions instead?

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?