<

How to make batch scripts only run as Administrator

Published on
3,394 Points
394 Views
Last Modified:
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
Comment
0 Comments

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Join & Write a Comment

Did you know PowerShell can save you time with SaaS platforms? Simply leverage RESTfulAPIs to build your own PowerShell modules. These will kill repetitive tickets and tabs, using the command Invoke-RestMethod. Tune into this webinar to learn how…
Check How effective MS Exchange Expert thinks Exchange Mailbox Recovery by SysTools IS. Visit the Official site to get detailed information:- https://www.systoolsgroup.com/exchange-recovery.html (https://www.systoolsgroup.com/exchange-recovery.h…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month