Jump to content
Sign in to follow this  
TomGL2

Batch File Requests Elevated Privileges

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

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...