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

后端 未结 15 962
陌清茗
陌清茗 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:35

    I do it this way:

    NET SESSION
    IF %ERRORLEVEL% NEQ 0 GOTO ELEVATE
    GOTO ADMINTASKS
    
    :ELEVATE
    CD /d %~dp0
    MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 1);close();"
    EXIT
    
    :ADMINTASKS
    (Do whatever you need to do here)
    EXIT
    

    This way it's simple and use only windows default commands. It's great if you need to redistribute you batch file.

    CD /d %~dp0 Sets the current directory to the file's current directory (if it is not already, regardless of the drive the file is in, thanks to the /d option).

    %~nx0 Returns the current filename with extension (If you don't include the extension and there is an exe with the same name on the folder, it will call the exe).

    There are so many replies on this post I don't even know if my reply will be seen.

    Anyway, I find this way simpler than the other solutions proposed on the other answers, I hope it helps someone.

    0 讨论(0)
  • 2020-11-22 04:38

    You can have the script call itself with psexec's -h option to run elevated.

    I'm not sure how you would detect if it's already running as elevated or not... maybe re-try with elevated perms only if there's an Access Denied error?

    Or, you could simply have the commands for the xcopy and reg.exe always be run with psexec -h, but it would be annoying for the end-user if they need to input their password each time (or insecure if you included the password in the script)...

    0 讨论(0)
  • 2020-11-22 04:38

    Following solution is clean and works perfectly.

    1. Download Elevate zip file from https://www.winability.com/download/Elevate.zip

    2. Inside zip you should find two files: Elevate.exe and Elevate64.exe. (The latter is a native 64-bit compilation, if you require that, although the regular 32-bit version, Elevate.exe, should work fine with both the 32- and 64-bit versions of Windows)

    3. Copy the file Elevate.exe into a folder where Windows can always find it (such as C:/Windows). Or you better you can copy in same folder where you are planning to keep your bat file.

    4. To use it in a batch file, just prepend the command you want to execute as administrator with the elevate command, like this:

     elevate net start service ...
    
    0 讨论(0)
提交回复
热议问题