Cannot start a ps1 file with BATCH using `call` or `start` - windows

Ive got issues with a batch command that wont start whatever i was to do about it, even using call wouldnt start it.
:choice2
set /P c1="text here [Y/N]? "
if /I "%c1%" EQU "Y" start "" /wait /high /max "Powershell.exe -executionpolicy remotesigned -File %batdir%batch\filename.ps1"
if /I "%c1%" EQU "N" goto :end
goto :choice2
Main requirement is that the %batdir% is in the first if line, because the batch runs from a flash drive.
Tried without %batdir%, wouldnt work either way.
Tried using different commands for the powershell.exe, tried using a direct dir of powershell, wouldnt work, always getting the "Cannot find file, make sure it is typed in properly.".
I would appreciate any help anyone could provide.

As you have not provided a Minimal Complete and Verifiable Example, this assumes that %batdir% was the location of the running batch file, which I've replaced with the appropriate %~dp0 variable. You should also note that I've also replaced your set /p command, because that is not the correct command to use for known single key input:
:choice2
"%SystemRoot%\System32\choice.exe" /M "text here"
If ErrorLevel 2 GoTo end
Start "" /Wait /High /Max "%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -ExecutionPolicy RemoteSigned -File "%~dp0batch\filename.ps1"
GoTo choice2
:end
Pause
I do not recommend the use of /High or /Max for this task, (including them only because you did). So because you said you also tried call, it seems to me as if you probably don't need to use start with those options either. If you just need to run the powershell script and wait for it to complete, before returning to the input prompt, try this modification:
:choice2
"%SystemRoot%\System32\choice.exe" /M "text here"
If ErrorLevel 2 GoTo end
"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -ExecutionPolicy RemoteSigned -File "%~dp0batch\filename.ps1"
GoTo choice2
:end
Pause

Related

Running Flutter/Dart commands in batch script halts execution [duplicate]

I'm trying to get my commit-build.bat to execute other .BAT files as part of our build process.
Content of commit-build.bat:
"msbuild.bat"
"unit-tests.bat"
"deploy.bat"
This seems simple enough, but commit-build.bat only executes the first item in the list (msbuild.bat).
I have run each of the files separately with no problems.
Use:
call msbuild.bat
call unit-tests.bat
call deploy.bat
When not using CALL, the current batch file stops and the called batch file starts executing. It's a peculiar behavior dating back to the early MS-DOS days.
All the other answers are correct: use call. For example:
call "msbuild.bat"
History
In ancient DOS versions it was not possible to recursively execute batch files. Then the call command was introduced that called another cmd shell to execute the batch file and returned execution back to the calling cmd shell when finished.
Obviously in later versions no other cmd shell was necessary anymore.
In the early days many batch files depended on the fact that calling a batch file would not return to the calling batch file. Changing that behaviour without additional syntax would have broken many systems like batch menu systems (using batch files for menu structures).
As in many cases with Microsoft, backward compatibility therefore is the reason for this behaviour.
Tips
If your batch files have spaces in their names, use quotes around the name:
call "unit tests.bat"
By the way: if you do not have all the names of the batch files, you could also use for to do this (it does not guarantee the correct order of batch file calls; it follows the order of the file system):
FOR %x IN (*.bat) DO call "%x"
You can also react on errorlevels after a call. Use:
exit /B 1 # Or any other integer value in 0..255
to give back an errorlevel. 0 denotes correct execution. In the calling batch file you can react using
if errorlevel neq 0 <batch command>
Use if errorlevel 1 if you have an older Windows than NT4/2000/XP to catch all errorlevels 1 and greater.
To control the flow of a batch file, there is goto :-(
if errorlevel 2 goto label2
if errorlevel 1 goto label1
...
:label1
...
:label2
...
As others pointed out: have a look at build systems to replace batch files.
If we want to open multiple command prompts then we could use
start cmd /k
/k: is compulsory which will execute.
Launching many command prompts can be done as below.
start cmd /k Call rc_hub.bat 4444
start cmd /k Call rc_grid1.bat 5555
start cmd /k Call rc_grid1.bat 6666
start cmd /k Call rc_grid1.bat 5570.
Try:
call msbuild.bat
call unit-tests.bat
call deploy.bat
You are calling multiple batches in an effort to compile a program.
I take for granted that if an error occurs:
1) The program within the batch will exit with an errorlevel;
2) You want to know about it.
for %%b in ("msbuild.bat" "unit-tests.bat" "deploy.bat") do call %%b|| exit /b 1
'||' tests for an errorlevel higher than 0. This way all batches are called in order but will stop at any error, leaving the screen as it is for you to see any error message.
If we have two batch scripts, aaa.bat and bbb.bat, and call like below
call aaa.bat
call bbb.bat
When executing the script, it will call aaa.bat first, wait for the thread of aaa.bat terminate, and call bbb.bat.
But if you don't want to wait for aaa.bat to terminate to call bbb.bat, try to use the START command:
START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
[/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
[/AFFINITY <hex affinity>] [/WAIT] [/B] [command/program]
[parameters]
Exam:
start /b aaa.bat
start /b bbb.bat
call msbuild.bat
call unit-tests.bat
call deploy.bat
using "&"
As you have noticed executing the bat directly without CALL,START, CMD /C causes to enter and execute the first file and then the process to stop as the first file is finished. Though you still can use & which will be the same as using command1 & command2 directly in the console:
(
first.bat
)&(
second.bat
)& (
third.bat
)&(
echo other commands
)
In a term of machine resources this will be the most efficient way though in the last block you won't be able to use command line GOTO,SHIFT,SETLOCAL.. and its capabilities will almost the same as in executing commands in the command prompt. And you won't be able to execute other command after the last closing bracket
Using CALL
call first.bat
call second.bat
call third.bat
In most of the cases it will be best approach - it does not create a separate process but has almost identical behaviour as calling a :label as subroutine. In MS terminology it creates a new "batch file context and pass control to the statement after the specified label. The first time the end of the batch file is encountered (that is, after jumping to the label), control returns to the statement after the call statement."
You can use variables set in the called files (if they are not set in a SETLOCAL block), you can access directly labels in the called file.
CMD /C, Pipes ,FOR /F
Other native option is to use CMD /C (the /C switch will force the called console to exit and return the control)
Something that cmd.exe is doing in non transparent way with using FOR /F against bat file or when pipes are used.
This will spawn a child process that will have all the environment ot the calling bat.
Less efficient in terms of resources but as the process is separate ,parsing crashes or calling an EXIT command will not stop the calling .bat
#echo off
CMD /c first.bat
CMD /C second.bat
::not so different than the above lines.
:: MORE,FINDSTR,FIND command will be able to read the piped data
:: passed from the left side
break|third.bat
START
Allows you more flexibility as the capability to start the scripts in separate window , to not wait them to finish, setting a title and so on. By default it starts the .bat and .cmd scripts with CMD /K which means that the spawned scripts will not close automatically.Again passes all the environment to the started scripts and consumes more resources than cmd /c:
:: will be executed in the same console window and will wait to finish
start "" /b /w cmd /c first.bat
::will start in a separate console window and WONT wait to be finished
:: the second console window wont close automatically so second.bat might need explicit exit command
start "" second.bat
::Will start it in a separate window ,but will wait to finish
:: closing the second window will cause Y/N prompt
:: in the original window
start "" /w third.cmd
::will start it in the same console window
:: but wont wait to finish. May lead to a little bit confusing output
start "" /b cmd /c fourth.bat
WMIC
Unlike the other methods from now on the examples will use external of the CMD.exe utilities (still available on Windows by default).
WMIC utility will create completely separate process so you wont be able directly to wait to finish. Though the best feature of WMIC is that it returns the id of the spawned process:
:: will create a separate process with cmd.exe /c
WMIC process call create "%cd%\first.bat","%cd%"
::you can get the PID and monitoring it with other tools
for /f "tokens=2 delims=;= " %%# in ('WMIC process call create "%cd%\second.bat"^,"%cd%" ^|find "ProcessId"') do (
set "PID=%%#"
)
echo %PID%
You can also use it to start a process on a remote machine , with different user and so on.
SCHTASKS
Using SCHTASKS provides some features as (obvious) scheduling , running as another user (even the system user) , remote machine start and so on. Again starts it in completely separate environment (i.e. its own variables) and even a hidden process, xml file with command parameters and so on :
SCHTASKS /create /tn BatRunner /tr "%cd%\first.bat" /sc ONCE /sd 01/01/1910 /st 00:00
SCHTASKS /Run /TN BatRunner
SCHTASKS /Delete /TN BatRunner /F
Here the PID also can acquired from the event log.
ScriptRunner
Offers some timeout between started scripts. Basic transaction capabilities (i.e. rollback on error) and the parameters can be put in a separate XML file.
::if the script is not finished after 15 seconds (i.e. ends with pause) it will be killed
ScriptRunner.exe -appvscript %cd%\first.bat -appvscriptrunnerparameters -wait -timeout=15
::will wait or the first called script before to start the second
:: if any of the scripts exit with errorcode different than 0 will try
:: try to restore the system in the original state
ScriptRunner.exe -appvscript second.cmd arg1 arg2 -appvscriptrunnerparameters -wait -rollbackonerror -appvscript third.bat -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror
To call a .bat file within a .bat file, use
call foo.bat
(Yes, this is silly, it would make more sense if you could call it with foo.bat, like you could from the command prompt, but the correct way is to use call.)
Simplest Way To Run Multiple Batch Files Parallelly
start "systemLogCollector" /min cmd /k call systemLogCollector.bat
start "uiLogCollector" /min cmd /k call uiLogCollector.bat
start "appLogCollector" /min cmd /k call appLogCollector.bat
Here three batch files are run on separate command windows in a minimized state. If you don't want them minimized, then remove /min. Also, if you don't need to control them later, then you can get rid of the titles. So, a bare-bone command will be- start cmd /k call systemLogCollector.bat
If you want to terminate them, then run these commands-
taskkill /FI "WindowTitle eq appLogCollector*" /T /F
taskkill /FI "WindowTitle eq uiLogCollector*" /T /F
taskkill /FI "WindowTitle eq systemLogCollector*" /T /F
Start msbuild.bat
Start unit-tests.bat
Start deploy.bat
If that doesn't work, replace start with call or try this:
Start msbuild.bat
Goto :1
:1
Start unit-tests.bat
Goto :2
:2
Start deploy.bat
Looking at your filenames, have you considered using a build tool like NAnt or Ant (the Java version). You'll get a lot more control than with bat files.
If you want to open many batch files at once you can use the call command. However, the call command closes the current bat file and goes to another. If you want to open many at once, you may want to try this:
#echo off
start cmd "call ex1.bat&ex2.bat&ex3.bat"
And so on or repeat start cmd "call..." for however many files. This works for Windows 7, but I am not sure about other systems.
Your script should be:
start "msbuild.bat"
start "unit-tests.bat"
start "deploy.bat"
Just use the call command! Here is an example:
call msbuild.bat
call unit-tests.bat
call deploy.bat
With correct quoting (this can be tricky sometimes):
start "" /D "C:\Program Files\ProgramToLaunch" "cmd.exe" "/c call ""C:\Program Files\ProgramToLaunch\programname.bat"""
1st arg - Title (empty in this case)
2nd arg - /D specifies starting directory, can be ommited if want the current working dir (such as "%~dp0")
3rd arg - command to launch, "cmd.exe"
4th arg - arguments to command, with doubled up quotes for the arguments inside it (this is how you escape quotes within quotes in batch)
Running multiple scripts in one I had the same issue. I kept having it die on the first one not realizing that it was exiting on the first script.
:: OneScriptToRunThemAll.bat
CALL ScriptA.bat
CALL ScriptB.bat
EXIT
:: ScriptA.bat
Do Foo
EXIT
::ScriptB.bat
Do bar
EXIT
I removed all 11 of my scripts EXIT lines and tried again and all 11 ran in order one at a time in the same command window.
:: OneScriptToRunThemAll.bat
CALL ScriptA.bat
CALL ScriptB.bat
EXIT
::ScriptA.bat
Do Foo
::ScriptB.bat
Do bar
I know I am a bit late to the party, but here is another way. That is, this method should wait until the first one is done, the second, and so on.
start "" /wait cmd.exe /c msbuild.bat
start "" /wait cmd.exe /c unit-tests.bat
start "" /wait cmd.exe /c deploy.bat
The only issue that may come out of using this method, is that with new instances of cmd.exe being spawned, is that Errorlevel checking is kept within in each instance of cmd.exe.
Or..
start "" /wait call msbuild.bat
start "" /wait call unit-tests.bat
start "" /wait call deploy.bat
Hope this helps.

Command Line - Wait for a Process to Finish

I'm installing a set of drivers in an unattended script. One of the drivers (Intel USB3 Drivers) kicks off the Windows Driver Finder application ("drvinst.exe") after it's finished. Then, when the nVidia Drivers try to run, they cancel out because that Wizard is still running in the background.
My current solution is this, but it is not very elegant:
:INSTALLLAPTOP79
.\ELAN\Touchpad\Setup.exe /s /a /s
.\Intel\Chipset\Setup.exe -s -norestart
.\Intel\Graphics\Setup.exe -s
.\Intel\MEI\Setup.exe -s
.\Intel\USB3\Setup.exe -s
.\Realtek\Audio\Setup.exe /s
.\Realtek\CardReader\Setup.exe /s
TIMEOUT 180
.\nVidia\Graphics\Setup.exe -n -s
GOTO :INSTALLLAPTOPWIFI
Basically if a system is slower than "normal" it will fail as the 180 seconds isn't enough. I could just increase this value but that is messy to me.
I'm basically looking for a way to do a "check" to see if the "drvinst.exe" is still running and if so wait for a set period - then do the check again.
Any ideas?
It's not guaranteed to work (it depends on how the installers launch the driver-finder) but:
start /wait command...
may do the trick. Be aware that if the command to be executed contains spaces, and needs to be wrapped in double-quotes, you'll need:
start /wait "" "c:\program files\something\..."
otherwise it will take the command as the title of the command-prompt.
#ECHO OFF
SETLOCAL
notepad
:waitloop
TASKLIST /fi "imagename eq notepad.exe" >NUL
IF ERRORLEVEL 1 timeout /t 1 /n&GOTO waitloop
GOTO :EOF
Here's a simple method waiting for notepad.exe to close. Adapt as you will...
#ECHO OFF
SETLOCAL
notepad
:waitloop
TASKLIST |find "notepad.exe" >NUL
IF ERRORLEVEL 1 timeout /t 1 /n&GOTO waitloop
GOTO :EOF
should work also
This works for me in Windows 10 (1903). Caveat: if you use it for a process that is running multiple times, it waits for all of them to finish before continuing.
Based on this answer by #Magoo which didn't work for me, but put me on the right track.
#ECHO OFF
notepad.exe
REM For the OP's original problem, put drvinst.exe instead of notepad.exe (here and below)
:waitloop
TASKLIST |find /I "notepad.exe" >NUL
IF ERRORLEVEL 1 GOTO endloop
REM echo Notepad running. Waiting 1 second...
timeout /t 1 /nobreak>NUL
goto waitloop
:endloop
echo Done!
i dont know if this is the best way to do it, but i know it works 100%
I use call in my scripts when i need it to wait.
:INSTALLLAPTOP79
Call \ELAN\Touchpad\Setup.exe /s /a /s
Call \Intel\Chipset\Setup.exe -s -norestart
Call \Intel\Graphics\Setup.exe -s
Call \Intel\MEI\Setup.exe -s
Call \Intel\USB3\Setup.exe -s
Call \Realtek\Audio\Setup.exe /s
Call \Realtek\CardReader\Setup.exe /s
Call \nVidia\Graphics\Setup.exe -n -s
GOTO :INSTALLLAPTOPWIFI
Call will make the script wait until the exe that's being ran is finished.
Not sure what purpose the . before the \ serves but you may need it if its there for a reason.

Prevent batch file from closing after it executes an external .exe program

Believe it or not, I've searched all over stackoverflow and Google and can't find an answer to this that works for me.
(Windows 7 64-bit) I'm trying to create a batch file that runs multiple programs, one at a time. Simple, right? It works great until it runs the first .exe program. After the GUI of the .exe program closes, the batch file/cmd window also closes. I don't want it to close; I want the rest of the batch file to run.
Inside the batch file, I've tried the following methods, but none of them prevent the batch file from closing:
Git-1.9.5-preview20141217.exe
Git-1.9.5-preview20141217.exe
pause
call Git-1.9.5-preview20141217.exe
pause
start Git-1.9.5-preview20141217.exe
pause
start "" /wait Git-1.9.5-preview20141217.exe
pause
start "" /w Git-1.9.5-preview20141217.exe
pause
start "" /w /b Git-1.9.5-preview20141217.exe
pause
Does anyone know another method I can try? Maybe I should just call a powershell command or even translate the whole batch file to powershell, but I was trying to avoid powershell so that this script would work on multiple versions of Windows.
EDIT
I should also mention that with the methods above, the script closes before the pause command can be executed.
EDIT
Here's the full script with the rest of the .exe programs:
:Git
#echo off
(
echo.
echo.
echo DOWNLOADING GIT...
)
powershell -Command "(New-Object Net.WebClient).DownloadFile('http://github.com/msysgit/msysgit/releases/download/Git-1.9.5-preview20141217/Git-1.9.5-preview20141217.exe', 'Git-1.9.5-preview20141217.exe')"
(
echo.
echo.
echo LAUNCHING GIT INSTALLATION PROGRAM...
echo.
echo !IMPORTANT! WHEN YOU REACH THE SCREEN 'Adjusting your PATH environment',
echo SELECT 'Use Git from the Windows Command Prompt'.
echo KEEP ALL OTHER OPTIONS AT THE DEFAULT SETTING.
echo.
echo AFTER READING THE INSTRUCTIONS ABOVE, PRESS ANY KEY TO CONTINUE
)
pause
Git-1.9.5-preview20141217.exe
pause
GOTO CheckOS
:CheckOS
IF EXIST "%PROGRAMFILES(X86)%" (GOTO 64BIT) ELSE (GOTO 32BIT)
:32BIT
(
echo.
echo.
echo 32 BIT
echo.
echo DOWNLOADING TORTOISEHG (MERCURIAL)...
)
powershell -Command "(New-Object Net.WebClient).DownloadFile('http://bitbucket.org/tortoisehg/files/downloads/tortoisehg-3.2.4-x86.msi', 'tortoisehg-3.2.4-x86.msi')"
(
echo.
echo.
echo LAUNCHING TORTOISEHG INSTALLATION PROGRAM...
)
tortoisehg-3.2.4-x86.msi
GOTO MingW
:64BIT
(
echo.
echo.
echo 64 BIT
echo.
echo DOWNLOADING TORTOISEHG (MERCURIAL)...
)
powershell -Command "(New-Object Net.WebClient).DownloadFile('http://bitbucket.org/tortoisehg/files/downloads/tortoisehg-3.2.4-x64.msi', 'tortoisehg-3.2.4-x64.msi')"
(
echo.
echo.
echo LAUNCHING TORTOISEHG INSTALLATION PROGRAM...
)
tortoisehg-3.2.4-x64.msi
GOTO MingW
:MingW
(
echo.
echo.
echo DOWNLOADING MINGW...
)
powershell -Command "(New-Object Net.WebClient).DownloadFile('http://downloads.sourceforge.net/project/mingwbuilds/mingw-builds-install/mingw-builds-install.exe?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fmingwbuilds%2F%3Fsource%3Dtyp_redirect&ts=1422376004&use_mirror=iweb', 'mingw-builds-install.exe')"
(
echo.
echo.
echo LAUNCHING MINGW INSTALLATION PROGRAM...
)
mingw-builds-install.exe
(
echo.
echo.
echo DONE! PRESS ANY KEY TO CLOSE.
)
pause
GOTO END
:END
For the lines that run the external .exe program, I've tried all 7 forms of the command that were listed at the beginning of this question, yet the script always closes before reaching the next pause command. I've also tried using cmd.exe /c and cmd.exe /k from the suggestions below, but unfortunately the script still quits before reaching the pause command.
EDIT
I figured out the problem (though not how to fix it). If I remove these lines:
GOTO CheckOS
:CheckOS
IF EXIST "%PROGRAMFILES(X86)%" (GOTO 64BIT) ELSE (GOTO 32BIT)
:32BIT
so that the following commands are under the same batch label, it works! But I'm not sure why including the :CheckOS label causes it to break. I've used this label in other batch scripts before, and they worked fine.
Nevermind, sorry. :S This only worked if the program had already been run. If it had already been run, a "modify, repair, or remove" screen popped up instead of an "install" screen. Apparently only the "install" screen closes the cmd.exe window.
FINAL EDIT
The parentheses were the problem. After removing them, everything else worked. Method number 1 at the beginning of this question works after removing the parentheses.
Try opening the executable in a new shell:
#echo off
cmd.exe /c Git-1.9.5-preview20141217.exe
echo Still here.
The /c switch tells the (new) shell to close when the program terminates. Execution of the batch script will be suspended until then.
For example:
#echo off
echo New window.
cmd.exe /c %WINDIR%\system32\notepad.exe
echo Window still open.
cmd.exe /c %WINDIR%\system32\notepad.exe
echo Window closed. You won't see this.

How to minimize the Command prompt condition based when it is executing the bat file?

I know how to start bat file with minimized window using other bat file.
Example:
first.bat
start /min second.bat
second.bat
#echo i'm minimized
But in my code base, run only one bat with minimized window. i'm using
start /min cmd /C "%~dpnx0"
this one, but it starts again my bat file. Please help me.Thanks in advance
It is possible to have a batch file launch itself in a minimized fashion. However, you'll need some way of telling the recursive invocation that it doesn't need to recurse again.
If your script doesn't already use command-line arguments, you could use one:
#echo off
rem blah blah blah
if "%1" == "/minimized" (goto min)
start /min "%~f0" /minimized
exit
:min
rem actual code goes here
If it does already use arguments, you could set an environment variable:
#echo off
rem blah blah blah
if defined MYSCRIPT_MINIMIZED (goto min)
set MYSCRIPT_MINIMIZED=yes
start /min "%~f0"
exit
:min
rem actual code goes here
Doubtless there are other techniques - those are the ones I could think of right now.

How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

I want my batch file to only run elevated. If not elevated, provide an option for the user to relaunch batch as elevated.
I'm writing a batch file to set a system variable, copy two files to a Program Files location, and start a driver installer. If a Windows 7/Windows Vista user (UAC enabled and even if they are a local admin) runs it without right-clicking and selecting "Run as Administrator", they will get 'Access Denied' copying the two files and writing the system variable.
I would like to use a command to automatically restart the batch as elevated if the user is in fact an administrator. Otherwise, if they are not an administrator, I want to tell them that they need administrator privileges to run the batch file. I'm using xcopy to copy the files and REG ADD to write the system variable. I'm using those commands to deal with possible Windows XP machines. I've found similar questions on this topic, but nothing that deals with relaunching a batch file as elevated.
There is an easy way without the need to use an external tool - it runs fine with Windows 7, 8, 8.1, 10 and 11 and is backwards-compatible too (Windows XP doesn't have any UAC, thus elevation is not needed - in that case the script just proceeds).
Check out this code (I was inspired by the code by NIronwolf posted in the thread Batch File - "Access Denied" On Windows 7?), but I've improved it - in my version there isn't any directory created and removed to check for administrator privileges):
::::::::::::::::::::::::::::::::::::::::::::
:: Elevate.cmd - Version 4
:: Automatically check & get admin rights
:: see "https://stackoverflow.com/a/12264592/1016343" for description
::::::::::::::::::::::::::::::::::::::::::::
#echo off
CLS
ECHO.
ECHO =============================
ECHO Running Admin shell
ECHO =============================
:init
setlocal DisableDelayedExpansion
set cmdInvoke=1
set winSysFolder=System32
set "batchPath=%~dpnx0"
rem this works also from cmd shell, other than %~0
for %%k in (%0) do set batchName=%%~nk
set "vbsGetPrivileges=%temp%\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 & 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
The script takes advantage of the fact that NET FILE requires administrator privilege and returns errorlevel 1 if you don't have it. The elevation is achieved by creating a script which re-launches the batch file to obtain privileges. This causes Windows to present the UAC dialog and asks you for the administrator account and password.
I have tested it with Windows 7, 8, 8.1, 10, 11 and with Windows XP - it works fine for all.
The advantage is, after the start point you can place anything that requires system administrator privileges, for example, if you intend to re-install and re-run a Windows service for debugging purposes (assumed that mypackage.msi is a service installer package):
msiexec /passive /x mypackage.msi
msiexec /passive /i mypackage.msi
net start myservice
Without this privilege elevating script, UAC would ask you three times for your administrator user and password - now you're asked only once at the beginning, and only if required.
If your script just needs to show an error message and exit if there aren't any administrator privileges instead of auto-elevating, this is even simpler: You can achieve this by adding the following at the beginning of your script:
#ECHO OFF & CLS & ECHO.
NET FILE 1>NUL 2>NUL & IF ERRORLEVEL 1 (ECHO You must right-click and select &
ECHO "RUN AS ADMINISTRATOR" to run this batch. Exiting... & ECHO. &
PAUSE & EXIT /D)
REM ... proceed here with admin rights ...
This way, the user has to right-click and select "Run as administrator". The script will proceed after the REM statement if it detects administrator rights, otherwise exit with an error. If you don't require the PAUSE, just remove it.
Important: NET FILE [...] EXIT /D) must be on the same line. It is displayed here in multiple lines for better readability!
On some machines, I've encountered issues, which are solved in the new version above already. One was due to different double quote handling, and the other issue was due to the fact that UAC was disabled (set to lowest level) on a Windows 7 machine, hence the script calls itself again and again.
I have fixed this now by stripping the quotes in the path and re-adding them later, and I've added an extra parameter which is added when the script re-launches with elevated rights.
The double quotes are removed by the following (details are here):
setlocal DisableDelayedExpansion
set "batchPath=%~0"
setlocal EnableDelayedExpansion
You can then access the path by using !batchPath!. It doesn't contain any double quotes, so it is safe to say "!batchPath!" later in the script.
The line
if '%1'=='ELEV' (shift & goto gotPrivileges)
checks if the script has already been called by the VBScript script to elevate rights, hence avoiding endless recursions. It removes the parameter using shift.
Update:
To avoid having to register the .vbs extension in Windows 10, I have replaced the line
"%temp%\OEgetPrivileges.vbs"
by
"%SystemRoot%\System32\WScript.exe" "%temp%\OEgetPrivileges.vbs"
in the script above; also added cd /d %~dp0 as suggested by Stephen (separate answer) and by Tomáš Zato (comment) to set script directory as default.
Now the script honors command line parameters being passed to it. Thanks to jxmallet, TanisDLJ and Peter Mortensen for observations and inspirations.
According to Artjom B.'s hint, I analyzed it and have replaced SHIFT by SHIFT /1, which preserves the file name for the %0 parameter
Added del "%temp%\OEgetPrivileges_%batchName%.vbs" to the :gotPrivileges section to clean up (as mlt suggested). Added %batchName% to avoid impact if you run different batches in parallel. Note that you need to use for to be able to take advantage of the advanced string functions, such as %%~nk, which extracts just the filename.
Optimized script structure, improvements (added variable vbsGetPrivileges which is now referenced everywhere allowing to change the path or name of the file easily, only delete .vbs file if batch needed to be elevated)
In some cases, a different calling syntax was required for elevation. If the script does not work, check the following parameters:
set cmdInvoke=0
set winSysFolder=System32
Either change the 1st parameter to set cmdInvoke=1 and check if that already fixes the issue. It will add cmd.exe to the script performing the elevation.
Or try to change the 2nd parameter to winSysFolder=Sysnative, this might help (but is in most cases not required) on 64 bit systems. (ADBailey has reported this). "Sysnative" is only required for launching 64-bit applications from a 32-bit script host (e.g. a Visual Studio build process, or script invocation from another 32-bit application).
To make it more clear how the parameters are interpreted, I am displaying it now like P1=value1 P2=value2 ... P9=value9. This is especially useful if you need to enclose parameters like paths in double quotes, e.g. "C:\Program Files".
If you want to debug the VBS script, you can add the //X parameter to WScript.exe as first parameter, as suggested here (it is described for CScript.exe, but works for WScript.exe too).
Bugfix provided by MiguelAngelo: batchPath is now returned correctly on cmd shell. This little script test.cmd shows the difference, for those interested in the details (run it in cmd.exe, then run it via double click from Windows Explorer):
#echo off
setlocal
set a="%~0"
set b="%~dpnx0"
if %a% EQU %b% echo running shell execute
if not %a% EQU %b% echo running cmd shell
echo a=%a%, b=%b%
pause
Useful links:
Meaning of special characters in batch file:Quotes ("), Bang (!), Caret (^), Ampersand (&), Other special characters
As jcoder and Matt mentioned, PowerShell made it easy, and it could even be embedded in the batch script without creating a new script.
I modified Matt's script:
:: Check privileges
net file 1>NUL 2>NUL
if not '%errorlevel%' == '0' (
powershell Start-Process -FilePath "%0" -ArgumentList "%cd%" -verb runas >NUL 2>&1
exit /b
)
:: Change directory with passed argument. Processes started with
:: "runas" start with forced C:\Windows\System32 workdir
cd /d %1
:: Actual work
I do it this way:
NET SESSION
IF %ERRORLEVEL% NEQ 0 GOTO ELEVATE
GOTO ADMINTASKS
:ELEVATE
CD /d %~dp0
MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 1);close();"
EXIT
:ADMINTASKS
(Do whatever you need to do here)
EXIT
This way it's simple and use only windows default commands.
It's great if you need to redistribute you batch file.
CD /d %~dp0 Sets the current directory to the file's current directory (if it is not already, regardless of the drive the file is in, thanks to the /d option).
%~nx0 Returns the current filename with extension (If you don't include the extension and there is an exe with the same name on the folder, it will call the exe).
There are so many replies on this post I don't even know if my reply will be seen.
Anyway, I find this way simpler than the other solutions proposed on the other answers, I hope it helps someone.
I am using Matt's excellent answer, but I am seeing a difference between my Windows 7 and Windows 8 systems when running elevated scripts.
Once the script is elevated on Windows 8, the current directory is set to C:\Windows\system32. Fortunately, there is an easy workaround by changing the current directory to the path of the current script:
cd /d %~dp0
Note: Use cd /d to make sure drive letter is also changed.
To test this, you can copy the following to a script. Run normally on either version to see the same result. Run as Admin and see the difference in Windows 8:
#echo off
echo Current path is %cd%
echo Changing directory to the path of the current script
cd %~dp0
echo Current path is %cd%
pause
Matt has a great answer, but it strips away any arguments passed to the script. Here is my modification that keeps arguments. I also incorporated Stephen's fix for the working directory problem in Windows 8.
#ECHO OFF
setlocal EnableDelayedExpansion
::net file to test privileges, 1>NUL redirects output, 2>NUL redirects errors
NET FILE 1>NUL 2>NUL
if '%errorlevel%' == '0' ( goto START ) else ( goto getPrivileges )
:getPrivileges
if '%1'=='ELEV' ( goto START )
set "batchPath=%~f0"
set "batchArgs=ELEV"
::Add quotes to the batch path, if needed
set "script=%0"
set script=%script:"=%
IF '%0'=='!script!' ( GOTO PathQuotesDone )
set "batchPath=""%batchPath%"""
:PathQuotesDone
::Add quotes to the arguments, if needed.
:ArgLoop
IF '%1'=='' ( GOTO EndArgLoop ) else ( GOTO AddArg )
:AddArg
set "arg=%1"
set arg=%arg:"=%
IF '%1'=='!arg!' ( GOTO NoQuotes )
set "batchArgs=%batchArgs% "%1""
GOTO QuotesDone
:NoQuotes
set "batchArgs=%batchArgs% %1"
:QuotesDone
shift
GOTO ArgLoop
:EndArgLoop
::Create and run the vb script to elevate the batch file
ECHO Set UAC = CreateObject^("Shell.Application"^) > "%temp%\OEgetPrivileges.vbs"
ECHO UAC.ShellExecute "cmd", "/c ""!batchPath! !batchArgs!""", "", "runas", 1 >> "%temp%\OEgetPrivileges.vbs"
"%temp%\OEgetPrivileges.vbs"
exit /B
:START
::Remove the elevation tag and set the correct working directory
IF '%1'=='ELEV' ( shift /1 )
cd /d %~dp0
::Do your adminy thing here...
You can have the script call itself with psexec's -h option to run elevated.
I'm not sure how you would detect if it's already running as elevated or not... maybe re-try with elevated perms only if there's an Access Denied error?
Or, you could simply have the commands for the xcopy and reg.exe always be run with psexec -h, but it would be annoying for the end-user if they need to input their password each time (or insecure if you included the password in the script)...
I use PowerShell to re-launch the script elevated if it's not. Put these lines at the very top of your script.
net file 1>nul 2>nul && goto :run || powershell -ex unrestricted -Command "Start-Process -Verb RunAs -FilePath '%comspec%' -ArgumentList '/c %~fnx0 %*'"
goto :eof
:run
:: TODO: Put code here that needs elevation
I copied the 'net name' method from #Matt's answer. His answer is much better documented and has error messages and the like. This one has the advantage that PowerShell is already installed and available on Windows 7 and up. No temporary VBScript (*.vbs) files, and you don't have to download tools.
This method should work without any configuration or setup, as long as your PowerShell execution permissions aren't locked down.
For some programs setting the super secret __COMPAT_LAYER environment variable to RunAsInvoker will work.Check this :
set "__COMPAT_LAYER=RunAsInvoker"
start regedit.exe
Though like this there will be no UAC prompting the user will continue without admin permissions.
I wrote gsudo, a sudo for windows: that elevates in the current console (no context switching to a new window), with a credentials cache (reduced UAC popups), and also elevates PowerShell commands.
It allows to elevate commands that require admin privileges, or the whole batch, if you want. Just prepend gsudo before anything that needs to run elevated.
Example batch file that elevates itself using gsudo:
EDIT: New one liner version that works with any windows language and avoids whoami issues:
net session >nul 2>nul & net session >nul 2>nul || gsudo "%~f0" && exit /b || exit /b
:: This will run as admin ::
Alternative (original version):
#echo off
rem Test if current context is already elevated:
whoami /groups | findstr /b BUILTIN\Administrators | findstr /c:"Enabled group" 1> nul 2>nul && goto :isadministrator
echo You are not admin. (yet)
:: Use gsudo to launch this batch file elevated.
gsudo "%~f0"
goto end
:isadministrator
echo You are admin.
echo (Do admin stuff now).
:end
Install:
via chocolatey: choco install gsudo
or scoop: scoop install gsudo
or grab it from github: https://github.com/gerardog/gsudo
See gsudo in action:
I recently needed a user-friendly approach and I came up with this, based on valuable insights from contributors here and elsewhere. Simply put this line at the top of your .bat script. Feedback welcome.
#pushd %~dp0 & fltmc | find "." && (powershell start '%~f0' ' %*' -verb runas 2>nul) && (popd & exit /b)
Intrepretation:
#pushd %~dp0 ensures a consistent working directory; supports UNC paths
& fltmc runs a native windows command that outputs an error when run unelevated
| find "." makes that error prettier, and causes nothing to output when elevated
&& ( if we successfully got an error because we're not elevated, do this...
powershell start invoke PowerShell and call the Start-Process cmdlet (start is an alias)
'%~f0' pass in the full path and name of this .bat file. Single quotes allow for spaces
' %*' pass in any and all arguments to this .bat file. Funky quoting and escape sequences probably won't work, but simple quoted strings should. The leading space is needed to prevent breaking things if no arguments are present
-verb runas don't just start the process... RunAs Administrator!
2>nul) discard PowerShell's unsightly error output if the UAC prompt is canceled/ignored
&& if we successfully invoked ourself with PowerShell, then...
NOTE: in the event we don't obtain elevation (user cancels UAC) then the && here allows the .bat to continue running without elevation, such that any commands that require it will fail but others will work just fine. If you want the script to simply exit instead of running unelevated, make this a single ampersand: &
(popd & exit /b) returns to the initial working directory on the command line and exits the initial .bat processing, because we don't need it anymore; we already have an elevated process running this .bat. The /b switch allows cmd.exe to remain open if the .bat was started from the command line – this has no effect if the .bat was double-clicked
When a CMD script needs Administrator rights and you know it, add this line to the very top of the script (right after any #ECHO OFF):
NET FILE > NUL 2>&1 || POWERSHELL -ex Unrestricted -Command "Start-Process -Verb RunAs -FilePath '%ComSpec%' -ArgumentList '/c \"%~fnx0\" %*'" && EXIT /b
The NET FILE checks for existing Administrator rights. If there are none, PowerShell starts the current script (with its arguments) in an elevated shell, and the non-elevated script closes.
If you don’t care about arguments then here’s a compact UAC prompting script that’s a single line long. It doesn’t pass arguments through since there’s no foolproof way to do that that handles every possible combination of poison characters.
net sess>nul 2>&1||(echo(CreateObject("Shell.Application"^).ShellExecute"%~0",,,"RunAs",1:CreateObject("Scripting.FileSystemObject"^).DeleteFile(wsh.ScriptFullName^)>"%temp%\%~nx0.vbs"&start wscript.exe "%temp%\%~nx0.vbs"&exit)
Paste this line under the #echo off in your batch file.
Explanation
The net sess>nul 2>&1 part is what checks for elevation. net sess is just shorthand for net session which is a command that returns an error code when the script doesn’t have elevated rights. I got this idea from this SO answer. Most of the answers here feature net file instead though which works the same. This command is fast and compatible on many systems.
The error level is then checked with the || operator. If the check succeeds then it creates and executes a WScript which re-runs the original batch file but with elevated rights before deleting itself.
Alternatives
The WScript file is the best approach being fast and reliable, although it uses a temporary file. Here are some other variations and their dis/ad-vantages.
PowerShell
net sess>nul 2>&1||(powershell saps '%0'-Verb RunAs&exit)
Pros:
Very short.
No temporary files.
Cons:
Slow. PowerShell can be slow to start up.
Spews red text when the user declines the UAC prompt. The PowerShell command could be wrapped in a try{...}catch{} to prevent this though.
Mshta WSH script
net sess>nul 2>&1||(start mshta.exe vbscript:code(close(Execute("CreateObject(""Shell.Application"").ShellExecute""%~0"",,,""RunAs"",1"^)^)^)&exit)
Pros:
Fast.
No temporary files.
Cons:
Not reliable. Some Windows 10 systems will block the script from running due to Windows Defender intercepting it as a potential trojan.
I pasted this in the beginning of the script:
:: BatchGotAdmin
:-------------------------------------
REM --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\icacls.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"
echo args = "" >> "%temp%\getadmin.vbs"
echo For Each strArg in WScript.Arguments >> "%temp%\getadmin.vbs"
echo args = args ^& strArg ^& " " >> "%temp%\getadmin.vbs"
echo Next >> "%temp%\getadmin.vbs"
echo UAC.ShellExecute "%~s0", args, "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs" %*
exit /B
:gotAdmin
if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
pushd "%CD%"
CD /D "%~dp0"
:--------------------------------------
Although not directly applicable to this question, because it wants some information for the user, google brought me here when I wanted to run my .bat file elevated from task scheduler.
The simplest approach was to create a shortcut to the .bat file, because for a shortcut you can set Run as administrator directly from the advanced properties.
Running the shortcut from task scheduler, runs the .bat file elevated.
Using powershell.
If the cmd file is long I use a first one to require elevation and then call the one doing the actual work.
If the script is a simple command everything may fit on one cmd file. Do not forget to include the path on the script files.
Template:
#echo off
powershell -Command "Start-Process 'cmd' -Verb RunAs -ArgumentList '/c " comands or another script.cmd go here "'"
Example 1:
#echo off
powershell -Command "Start-Process 'cmd' -Verb RunAs -ArgumentList '/c "powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\BIN\x.ps1"'"
Example 2:
#echo off
powershell -Command "Start-Process 'cmd' -Verb RunAs -ArgumentList '/c "c:\bin\myScript.cmd"'"
One-liner batch user elevation (with arguments)
Here is my one-liner version for this age-old question of batch user elevation which is still relevant today.
Simply add the code to the top of your batch script and you're good to go.
Silent
This version does not output anything nor pause execution on error.
#setlocal disabledelayedexpansion enableextensions
#echo off
:: Admin check
fltmc >nul 2>nul || set _=^"set _ELEV=1^& cd /d """%cd%"""^& "%~f0" %* ^"&&((if "%_ELEV%"=="" ((powershell -nop -c start cmd -args '/d/x/s/v:off/r',$env:_ -verb runas >nul 2>nul) || (mshta vbscript:execute^("createobject(""shell.application"").shellexecute(""cmd"",""/d/x/s/v:off/r ""&createobject(""WScript.Shell"").Environment(""PROCESS"")(""_""),,""runas"",1)(window.close)"^) >nul 2>nul)))& exit /b)
Verbose
A verbose version which tells the user that admin privileges are being requested and pauses on error before exiting.
#setlocal disabledelayedexpansion enableextensions
#echo off
:: Admin check
fltmc >nul 2>nul || set _=^"set _ELEV=1^& cd /d """%cd%"""^& "%~f0" %* ^"&&((if "%_ELEV%"=="" (echo Requesting administrator privileges...&((powershell -nop -c start cmd -args '/d/x/s/v:off/r',$env:_ -verb runas >nul 2>nul) || (mshta vbscript:execute^("createobject(""shell.application"").shellexecute(""cmd"",""/d/x/s/v:off/r ""&createobject(""WScript.Shell"").Environment(""PROCESS"")(""_""),,""runas"",1)(window.close)"^) >nul 2>nul))) else (echo This script requires administrator privileges.& pause))& exit /b)
echo Has admin permissions
echo Working dir: "%cd%"
echo Script dir: "%~dp0"
echo Script path: "%~f0"
echo Args: %*
pause
Method of operation
Uses fltmc to check for administrator privileges. (system component, included in Windows 2000+)
If user already has administrator privileges, continues operation normally.
If not, spawns an elevated version of itself using either:
powershell (optional Windows feature, included in Windows 7+ by default, can be uninstalled/otherwise not available, can be installed on Windows XP/Vista)
mshta (system component, included in Windows 2000+)
If fails to acquire elevation, stops execution (instead of looping endlessly).
What sets this solution apart from others?
There are literally hundreds of variations around for solving this issue but everything I've found so far have their shortcomings and this is an attempt of solving most of them.
Compatibility. Using fltmc as the means of checking for privileges and either powershell or mshta for elevation works with every Windows version since 2000 and should cover most system configurations.
Does not write any extra files.
Preserves current working directory. Most of the solutions found conflate "script directory" with "working directory" which are totally different concepts. If you want to use "script directory" instead, replace %cd% with %~dp0. Some people advocate using pushd "%~dp0" instead so paths inside networked UNC paths like "\\SOMEONES-PC\share" will work but that will also automagically map that location to a drive letter (like Y:) which might or might not be what you want.
Stops if unable to acquire elevation. This can happen because of several reasons, like user clicking "No" on the UAC prompt, UAC being disabled, group policy settings, etc. Many other solutions enter an endless loop on this point, spawning millions of command prompts until the heat death of the universe.
Supports (most of) command-line arguments and weird paths. Stuff like ampersands &, percent signs %, carets ^ and mismatching amount of quotes """'. You still definitely CAN break this by passing a sufficiently weird combinations of those, but that is an inherent flaw of Windows' batch processing and cannot really be worked around to always work with any combination. Most typical use-cases should be covered though and arguments work as they would without the elevation script.
Known issues
If you enter a command-line argument that has a mismatched amount of double-quotes (i.e. not divisible by 2), an extra space and a caret ^ will be added as a last argument. For example "arg1" arg2" """" "arg3" will become "arg1" arg2" """" "arg3" ^. If that matters for your script, you can add logic to fix it, f.ex. check if _ELEV=1 (meaning that elevation was required) and then check if the last character of argument list is ^ and/or amount of quotes is mismatched and remove the misbehaving caret.
Example script for logging output to file
You cannot easily use > for stdout logging because on elevation a new cmd window is spawned and execution context switched.
You can achieve it by passing increasingly weird combinations of escape characters, like elevate.bat testarg ^^^> test.txt but then you would need to make it always spawn the new cmd window or add logic to strip out the carets, all of which increases complexity and it would still break in many scenarios.
The best and easiest way would be simply adding the logging inside your batch script, instead of trying to redirect from command line. That'll save you a lot of headache.
Here is an example how you can easily implement logging for your script:
#setlocal disabledelayedexpansion enableextensions
#echo off
:: Admin check
fltmc >nul 2>nul || set _=^"set _ELEV=1^& cd /d """%cd%"""^& "%~f0" %* ^"&&((if "%_ELEV%"=="" (echo Requesting administrator privileges...&((powershell -nop -c start cmd -args '/d/x/s/v:off/r',$env:_ -verb runas >nul 2>nul) || (mshta vbscript:execute^("createobject(""shell.application"").shellexecute(""cmd"",""/d/x/s/v:off/r ""&createobject(""WScript.Shell"").Environment(""PROCESS"")(""_""),,""runas"",1)(window.close)"^) >nul 2>nul))) else (echo This script requires administrator privileges.& pause))& exit /b)
set _log=
set _args=%*
if not defined _args goto :noargs
set _args=%_args:"=%
set _args=%_args:(=%
set _args=%_args:)=%
for %%A in (%_args%) do (if /i "%%A"=="-log" (set "_log=>> %~n0.log"))
:noargs
if defined _log (echo Logging to file %~n0.log) else (echo Logging to stdout)
echo Has admin permissions %_log%
echo Working dir: "%cd%" %_log%
echo Script dir: "%~dp0" %_log%
echo Script path: "%~f0" %_log%
echo Args: %* %_log%
echo Hello World! %_log%
pause
Run: logtest.bat -log
By adding argument -log , the output will be logged to a file instead of stdout.
Closing thoughts
It bewilders me how a simple "ELEVATE" instruction has not been introduced to batch even after 15 years of UAC existing. Maybe one day Microsoft will get their shit together. Until then, we have to resort to using these hacks.
Try this:
#echo off
CLS
:init
setlocal DisableDelayedExpansion
set cmdInvoke=1
set winSysFolder=System32
set "batchPath=%~0"
for %%k in (%0) do set batchName=%%~nk
set "vbsGetPrivileges=%temp%\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 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 & cd /d %~dp0
if '%1'=='ELEV' (del "%vbsGetPrivileges%" 1>nul 2>nul & shift /1)
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
If you need information on that batch file, run the HTML/JS/CSS Snippet:
document.getElementsByTagName("data")[0].innerHTML="ElevateBatch, version 4, release<br>Required Commands:<ul><li>CLS</li><li>SETLOCAL</li><li>SET</li><li>FOR</li><li>NET</li><li>IF</li><li>ECHO</li><li>GOTO</li><li>EXIT</li><li>DEL</li></ul>It auto-elevates the system and if the user presses No, it just doesn't do anything.<br>This CANNOT be used to create an Elevated Explorer.";
data{font-family:arial;text-decoration:none}
<data></data>
%1 start "" mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c pushd ""%~dp0"" && ""%~s0"" ::","","runas",1)(window.close)&&exit
Following solution is clean and works perfectly.
Download Elevate zip file from https://www.winability.com/download/Elevate.zip
Inside zip you should find two files: Elevate.exe and Elevate64.exe. (The latter is a native 64-bit compilation, if you require that, although the regular 32-bit version, Elevate.exe, should work fine with both the 32- and 64-bit versions of Windows)
Copy the file Elevate.exe into a folder where Windows can always find it (such as C:/Windows). Or you better you can copy in same folder where you are planning to keep your bat file.
To use it in a batch file, just prepend the command you want to execute as administrator with the elevate command, like this:
elevate net start service ...

Resources