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

后端 未结 15 1203
陌清茗
陌清茗 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.

提交回复
热议问题