<

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

How to make batch scripts only run as Administrator

Published on
3,464 Points
464 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

Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

Join & Write a Comment

Overview of OneDrive and collaboration.
Watch this simple and effective video tutorial to extract attachments from Outlook 2007 and try this easy method by yourself. No need to go anywhere, just watch the video and export attachments from Outlook in few simple steps. To know more, click h…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month