Batch - Check admin right, run as admin

978 views Asked by At

I've changed something on my batch file, how can I get it started as administrator if a user press a key?

    echo Checking for Administrator elevation...
openfiles > NUL 2>&1
if %errorlevel%==0 (
    echo Elevation found! Proceeding...
    goto menu
) else (
    echo You are not running as Administrator...
    echo This batch cannot do it's job without elevation!
    echo.
    echo Right-click and select ^'Run as Administrator^' and try again...
    echo.
    echo Press any key to exit...
    pause > NUL
    exit
)

I know that it currently closes the script when there is no admin right, I want to start it as admin without closing it again.

1

There are 1 answers

0
Korkel On
    :elevatecheck
color 0c
cls
echo Starting the Windows Toolkit as administrator...
echo.
echo If asked to allow, choose ^YES^...
openfiles > NUL 2>&1
if %errorlevel%==0 (
echo.
cls
    echo You started the Windows Toolkit as administrator...
    timeout /t 2 >nul 2>&1 /nobreak
    echo.
    echo Windows Toolkit is starting...
    timeout /t 3 >nul 2>&1 /nobreak
    goto menu
) else (
    :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
goto menu
)
menu

This solved my problem.