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

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

    I use PowerShell to re-launch the script elevated if it's not. Put these lines at the very top of your script.

    net file 1>nul 2>nul && goto :run || powershell -ex unrestricted -Command "Start-Process -Verb RunAs -FilePath '%comspec%' -ArgumentList '/c %~fnx0 %*'"
    goto :eof
    :run
    :: TODO: Put code here that needs elevation
    

    I copied the 'net name' method from @Matt's answer. His answer is much better documented and has error messages and the like. This one has the advantage that PowerShell is already installed and available on Windows 7 and up. No temporary VBScript (*.vbs) files, and you don't have to download tools.

    This method should work without any configuration or setup, as long as your PowerShell execution permissions aren't locked down.

提交回复
热议问题