Batch file - Run as administrator, if not delete batch file?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Rubl7
Posts: 5
Joined: 10 Mar 2013 06:16

Batch file - Run as administrator, if not delete batch file?

#1 Post by Rubl7 » 10 Mar 2013 06:40

Hi I have made a batch file which I need to run as administrator. For that purpose I use this script,

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

abc0502
Posts: 1007
Joined: 26 Oct 2011 22:38
Location: Egypt

Re: Batch file - Run as administrator, if not delete batch f

#2 Post by abc0502 » 10 Mar 2013 06:58

you can make the batch create a file if it was run as an administrator, so before the batch exit it check to see if that file was created or not, if it wasn't that mean the batch didn't run in administrator mode and then you delete the batch, if it was run in administrator mode then the file must be exist and it then just exit.

and final note, make sure your batch delete the file if it finds it after every thing is done to make sure every thing runs ok when you run this batch again.

Post Reply