Solved Batch file request admin

April 18, 2013 at 11:16:12
Specs: Windows 7 HomePremium 64bit, I5 3570k / 16GB
I have a batch file that requires administrative privileges to perform most of its task for which it has this bit of code to do that.

>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
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 "%~s0", "%params%", "", "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"

The above code is put in the top of out batch file.
When it runs it request Admin and performs its task.
Only problem is that it opens up another command prompt with out batch in it and closes the one I opened to get it to open the other one.

What we would like is the batch file to open, ask for admin, then continue to run in the same cmd window. If that is possible.


See More: Batch file request admin

Report •


#1
April 18, 2013 at 12:50:10
It should still run ok as far as I can tell. Why must it stay in the same CMD window? Any commands you put after the bit of script you have above should run after the file has asked for admin rights. Is your Batch File not doing what you want?

I cleaned up your code a little bit for my use, but I added it to a batch file I already had and it seemed to work exactly as it should... Here's what I used:

@echo off
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' NEQ '0' (
    goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
	if exist "%temp%\getadmin.vbs" del "%temp%\getadmin.vbs"
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    echo UAC.ShellExecute "%~s0", "", "", "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"


Report •

#2
April 18, 2013 at 20:11:05
It works perfectly fine- its just that the people working on the batch file would like to keep it as minimalistic as possible. It does take two but the first is closed immediately but we had hoped it would be able to make use of just one window.

Report •

#3
April 19, 2013 at 06:56:54
✔ Best Answer
Technically the batch script doesn't start until after the first window has disappeared. The first window is just getting admin access for the second window which means you can't have an admin cmd window without the first cmd window. Also, I believe the only way to just have one window pop open and stay open is if you get rid of the top part of your script that asks for admin and just right-hand click on your batch file and click 'Run as Administrator'.

Report •

Related Solutions


Ask Question