Reputation: 1
Hi I have made a batch file which I need to run as administrator. For that purpose I use this script, which I took from here (StackOverflow).
But what I want, is if the user choose not to run as administrator (click NO to UAC), then the program will exit, and the batch will delete it selves automatically.
The command for the batch file to delete it selves is "del %0", but I need help as to where in this script, I can put this command. I tried to put it with "@exit /B", but then the batch file will delete if you press either YES or NO to UAC, and then the rest of the batch file cannot execute
Anybody can help figure out how to only run the command "del %0", when a user press "NO" to UAC?
@echo off
: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
Thanks guys Rune
Upvotes: 0
Views: 1931
Reputation: 1033
I know it's an old question but it's still useful to have a solution posted.
If you have Powershell installed you don't need to create a new vbs script and the ERRORLEVEL can be checked to detect if the UAC prompt was canceled or not.
Just put this in your script:
@echo off
:checkPrivileges
NET FILE 1>NUL 2>NUL
if '%errorlevel%' == '0' ( goto gotPrivileges
) else ( powershell "saps -filepath %0 -verb runas" >nul 2>&1)
if NOT '%errorlevel%' == '0' call :deleteSelf
exit /b
:deleteSelf
start /b "" cmd /c del "%~f0"&exit /b
REM No need for this label
::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
The delete method I took from dbenham's post here
Upvotes: 0
Reputation: 24585
If I understand your question, you need a way to detect if the UAC prompt was canceled. You can detect this if you use my Elevate32.exe or Elevate64.exe (download ElevationToolkit1.zip) program with the -w option, which will return an exit code of 1223 (ERROR_CANCELLED) if you cancel the UAC prompt.
Bill
Upvotes: 1