Windows Batch Scripting - Elevate.cmd
I already made this mistake several times. UAC is turned on and I launch a Command Prompt to perform some activities. However, some actions will eventually fail as we don't have Administrative privileges.
In the past I launched a new Command Prompt (elevated, this time) and navigated back to the original folder to try again. Today I proudly present a script, which will do this for you!
Let's start with the technical difficulties. If the current command prompt is already elevated, we want no change. We want the new command prompt to be in the same folder as the un-elevated was. Normally this is easy, except if the working directory is on a network share... as elevated command prompts have no access to these resources.
NET FILE > nul 2>&1
IF NOT ERRORLEVEL 1 GOTO :eof
ECHO @ECHO OFF > %TEMP%\el_%USERNAME%.cmd
FOR /F "tokens=1,2,3 delims= " %%a IN ('NET USE ^| FIND "\\"') DO (
ECHO %%b | FIND ":" > nul
IF ERRORLEVEL 1 (
ECHO NET USE %%b >> %TEMP%\el_%USERNAME%.cmd
) ELSE (
ECHO NET USE %%b %%c >> %TEMP%\el_%USERNAME%.cmd
ECHO CLS >> %TEMP%\el_%USERNAME%.cmd
ECHO VER >> %TEMP%\el_%USERNAME%.cmd
ECHO CD /d %CD% >> %TEMP%\el_%USERNAME%.cmd
ECHO START /B "" cmd.exe /c DEL %TEMP%\el_%USERNAME%.cmd >> %TEMP%\el_%USERNAME%.cmd
POWERSHELL "saps -filepath %SYSTEMROOT%\System32\cmd.exe -ArgumentList ('/k','%TEMP%\el_%USERNAME%.cmd') -verb runas" > nul 2>&1
Save the above code as Elevate.cmd and copy it to C:\Windows for example. All you have to do now is to enter "elevate" at any command prompt and the magic will start to happen! The script itself is quite straightforward, I used different techniques around the Internet to create my version.
First, we use the NET FILE command to check if the current command prompt is already elevated. If yes, the script quits as no further actions are needed. If no, then we start to write a script... with the script! I dump all network resources, and make the new script to map them. After we clear the screen and execute the VER command (so it is similar to the original banner). The working directory is being changed to the original one, and then the temporary script will delete itself as it's no longer needed.
When the temporary script is done it is launched elevated by PowerShell, and finally the original command prompt is closed.