Run with elevated permissions

When a script is run with elevated permissions several aspects of the user environment may change: The current directory, the current TEMP folder and any mapped drives will be disconnected.

The script below will check if it is running with elevated (Admin) permissions, if not the script will popup a UAC prompt and relaunch itself. The script saves the current drive mappings and then re-maps them once the session has been elevated.

@Echo off
Set _tempfile=%LocalAppData%\SaveDrives.txt
Set _tempvbs=%LocalAppData%\getadmin.vbs

:: Check for admin permissions
Net Session >nul 2>&1
:: If error flag set, we do not have admin.
   Echo Requesting administrative privileges...
   Goto sub_elevate
) Else ( Goto sub_main )


:: Save the current drive mappings to a temp file
   Del %_tempfile% 2>Nul
   For /f "tokens=2" %%G in ('net use ^| find ":"') do (call :sub_save_drive %%G)

:: Create a temporary VBScript
   Echo Set objShell = CreateObject^("Shell.Application"^) > %_tempvbs%
   Echo objShell.ShellExecute "%~f0", "", "", "runas", 1 >> %_tempvbs%

:: Relaunch this script 'As Admin'
   cscript "%_tempvbs%" //nologo
   Exit /B

   Set _drive=%1
   For /f "tokens=2,*" %%I in ('Net Use %_drive% ^|Find "\\"') Do (Set _Path=%%J)
   Echo %_drive%~%_Path%>>%_tempfile%
   Goto :eof

:: At this point we should be running under an Admin token

If exist "%_tempvbs%" ( Del "%_tempvbs%" )

:: Re-Map the drives listed in the temp file (if any)
For /f "tokens=1,2 delims=~" %%G in (%_tempfile%) do (Net Use %%G /delete /y & Net Use %%G "%%H" /persistent:no)

If exist "%_tempfile%" ( Del "%_tempfile%" )

Echo == List the current drive mappings ==
Net Use
:: ** Add extra commands you want to run elevated here **

“It is impossible to genuinely elevate yourself by pushing another person lower” - Guy Finley


Source: The script above is losely based on batchgotadmin plus some ideas from this forum thread.
.ShellExecute - Run a script/application in the Windows Shell (elevated)
DriveMap - Connect to a network file share
Elevation PowerToys for Windows Vista + Elevation blog

© Copyright 1999-2013
Some rights reserved