Jump to content

Change Mode

Batch File Requests Elevated Privileges


TomGL2
 Share

Recommended Posts

Some batch files require administrator's rights to perform their tasks, such as writing to the HKLM and HKCR hives, performing disk maintenance, etc. It's easy to forget which do and which don't, leading to some annoying false starts.

 

Starting the batch file with this code fragment at the top will invoke the "Run As" prompt and rerun the batch file as the selected user.

@echo off

:: Code sample - Request elevated privileges for batch

:: :: :: :: :: :: :: :: :: :: :: ::  

:: Code here runs as logged-on user

:: :: :: :: :: :: :: :: :: :: :: ::  

net user "%username%" | find /i "group" | find /i "administrators" > NUL

if NOT errorlevel 1 goto Elev'd

echo Started with %username%'s privileges

set tmpVbs="%temp%\~elevTmp.vbs"

echo CreateObject("Shell.Application").ShellExecute "%comspec%", "/c "%0"", , "runas">%tmpVbs%

start "" /w %tmpVbs%

del %tmpVbs%

exit /b

:Elev'd

echo.

echo Running with %username%'s privileges

:: :: :: :: :: :: :: :: :: :: :: ::  

:: Code requiring elevation follows

:: :: :: :: :: :: :: :: :: :: :: ::  

pause

In use, you would of course remove "echo Started with..." and "Running with...", "pause", and the "::" comments.

Edited by TomGL2
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...