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

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

    I pasted this in the beginning of the script:

    :: BatchGotAdmin
    :-------------------------------------
    REM  --> Check for permissions
    >nul 2>&1 "%SYSTEMROOT%\system32\icacls.exe" "%SYSTEMROOT%\system32\config\system"
    
    REM --> If error flag set, we do not have admin.
    if '%errorlevel%' NEQ '0' (
        echo Requesting administrative privileges...
        goto UACPrompt
    ) else ( goto gotAdmin )
    
    :UACPrompt
        echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
        echo args = "" >> "%temp%\getadmin.vbs"
        echo For Each strArg in WScript.Arguments >> "%temp%\getadmin.vbs"
        echo args = args ^& strArg ^& " "  >> "%temp%\getadmin.vbs"
        echo Next >> "%temp%\getadmin.vbs"
        echo UAC.ShellExecute "%~s0", args, "", "runas", 1 >> "%temp%\getadmin.vbs"
    
        "%temp%\getadmin.vbs" %*
        exit /B
    
    :gotAdmin
        if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
        pushd "%CD%"
        CD /D "%~dp0"
    :--------------------------------------
    

提交回复
热议问题