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

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

    As jcoder and Matt mentioned, PowerShell made it easy, and it could even be embedded in the batch script without creating a new script.

    I modified Matt's script:

    :: Check privileges 
    net file 1>NUL 2>NUL
    if not '%errorlevel%' == '0' (
        powershell Start-Process -FilePath "%0" -ArgumentList "%cd%" -verb runas >NUL 2>&1
        exit /b
    )
    
    :: Change directory with passed argument. Processes started with
    :: "runas" start with forced C:\Windows\System32 workdir
    cd /d %1
    
    :: Actual work
    

提交回复
热议问题