How to make batch scripts only run as Administrator

Published:
Updated:
This is a fine trick which I've found useful many times, when you just don't want to accidentally run a batch script or the commands needs administrator rights.

I am not an hardcore scripter and this is probably not for hardcore scripters.


I have for quite some time searched for a handy way of not accidentally running batch scripts that requires administrative previlieges, WITHOUT it being able to run the first few commands that doesn't need administrative previlieges, and just ends up messning things up.


Anyway, here it is, I did not find it on google, I scavanged it from a batch script that originally started a program.

Where it says "Insert commands here" at row 7 is where your code goes. To clarify, you delete "Insert commands here" and put your code where that line was.


@echo off

::call :check_Permissions
call :checkperms
if "%ADMIN%"=="FAIL" goto :EOF

Insert commands here

:check_Permissions
:: net session >nul 2>&1
:: sfc 2>&1 | find /i "/SCANNOW"
setlocal enabledelayedexpansion
fsutil dirty query %systemdrive% >nul
if not errorLevel 1 (
echo Administrative permissions confirmed.
) else (
echo You need to run as Administrator [use right-click - Run as administrator].
echo.
echo If you ran as Administrator, please check your PATH environment variable includes the Windows\system32 folder.
echo.
echo PATH VARIABLE = "!PATH!"
echo.
color cf
pause
Set ADMIN=FAIL
)
endlocal
goto :eof

:checkperms
set randname=%random%%random%%random%%random%%random%
md %windir%\%randname% 2>nul
if %errorlevel%==0 (echo Administrative permissions confirmed.
goto end)
if %errorlevel%==1 (
echo You need to run as Administrator [use right-click - Run as administrator].
echo.
color cf
pause
Set ADMIN=FAIL
goto end)
goto checkperms
:end
rd %windir%\%randname% 2>nul
goto :eof

If you found any problems in my grammar or in the commands, just tell me, thanks!

0
1,043 Views

Comments (0)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.