I want my batch file to only run elevated. If not elevated, provide an option for the user to relaunch batch as elevated.
I\'m writing a batch file to set a system v
If you don’t need to pass arguments through then here’s a compact UAC prompting script that’s a single line long. This does a similar thing as the elevation script in the top voted answer but doesn’t pass arguments through since there’s no foolproof way to do that that handles every possible combination of poison characters.
net sess>nul 2>&1||(echo(CreateObject("Shell.Application"^).ShellExecute"%~0",,,"RunAs",1:CreateObject("Scripting.FileSystemObject"^).DeleteFile(wsh.ScriptFullName^)>"%temp%\%~nx0.vbs"&start wscript.exe "%temp%\%~nx0.vbs"&exit)
Place this just below the @echo off
line in your batch script.
The net sess>nul 2>&1
part is what checks for elevation. net sess
is just shorthand for net session
which is a command that returns an error code when the script doesn’t have elevated rights. I got this idea from this SO answer. Most of the answers here use net file
instead though which works the same.
The error level is then checked with the ||
operator. If the check succeeds then it creates and executes a WScript which re-runs the original batch file but with elevated rights before deleting itself.
The WScript file is the best approach being fast and reliable, although it uses a temporary file. Here are some other variations and their dis/advantages.
net sess>nul 2>&1||(powershell saps '%0'-Verb RunAs&exit)
Pros:
Cons:
try..catch
to prevent this though.net sess>nul 2>&1||(start mshta.exe vbscript:code(close(Execute("CreateObject(""Shell.Application"").ShellExecute""%~0"",,,""RunAs"",1"^)^)^)&exit)
Pros:
Cons: