Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a batch file to run cmd as administrator

Tags:

batch-file

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

like image 960
JChan Avatar asked Jul 17 '12 14:07

JChan


People also ask

How can I Run cmd as administrator?

Type cmd, right-click the Command Prompt tile, and then click Run as administrator.

Is it possible to automatically Run a batch file as administrator?

Yes, you're able to run a batch file with administrative rights.


2 Answers

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: 
like image 137
Lokesh Kumar Avatar answered Oct 27 '22 11:10

Lokesh Kumar


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.

like image 37
Bali C Avatar answered Oct 27 '22 11:10

Bali C