How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

后端 未结 15 960
陌清茗
陌清茗 2020-11-22 03:59

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

15条回答
  •  醉酒成梦
    2020-11-22 04:27

    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.

    Explanation

    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.

    PowerShell

    net sess>nul 2>&1||(powershell saps '%0'-Verb RunAs&exit)
    

    Pros:

    • Very short.
    • No temporary files.

    Cons:

    • Slow. PowerShell can be very slow to start up.
    • Spews red text when the user declines the UAC prompt. The PowerShell command could be wrapped in a try..catch to prevent this though.

    Mshta WSH script

    net sess>nul 2>&1||(start mshta.exe vbscript:code(close(Execute("CreateObject(""Shell.Application"").ShellExecute""%~0"",,,""RunAs"",1"^)^)^)&exit)
    

    Pros:

    • Fast.
    • No temporary files.

    Cons:

    • Not reliable. Some Windows 10 machines will block the script from running as Windows Defender intercepts it as a potential trojan.

提交回复
热议问题