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

后端 未结 15 942
陌清茗
陌清茗 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 am using Matt's excellent answer, but I am seeing a difference between my Windows 7 and Windows 8 systems when running elevated scripts.

    Once the script is elevated on Windows 8, the current directory is set to C:\Windows\system32. Fortunately, there is an easy workaround by changing the current directory to the path of the current script:

    cd /d %~dp0
    

    Note: Use cd /d to make sure drive letter is also changed.

    To test this, you can copy the following to a script. Run normally on either version to see the same result. Run as Admin and see the difference in Windows 8:

    @echo off
    echo Current path is %cd%
    echo Changing directory to the path of the current script
    cd %~dp0
    echo Current path is %cd%
    pause
    

提交回复
热议问题