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

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

    Try this:

    @echo off
    CLS
    :init
    setlocal DisableDelayedExpansion
    set cmdInvoke=1
    set winSysFolder=System32
    set "batchPath=%~0"
    for %%k in (%0) do set batchName=%%~nk
    set "vbsGetPrivileges=%temp%\OEgetPriv_%batchName%.vbs"
    setlocal EnableDelayedExpansion
    :checkPrivileges
    NET FILE 1>NUL 2>NUL
    if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )
    :getPrivileges
    if '%1'=='ELEV' (echo ELEV & shift /1 & goto gotPrivileges)
    ECHO.
    ECHO Set UAC = CreateObject^("Shell.Application"^) > "%vbsGetPrivileges%"
    ECHO args = "ELEV " >> "%vbsGetPrivileges%"
    ECHO For Each strArg in WScript.Arguments >> "%vbsGetPrivileges%"
    ECHO args = args ^& strArg ^& " "  >> "%vbsGetPrivileges%"
    ECHO Next >> "%vbsGetPrivileges%"
    if '%cmdInvoke%'=='1' goto InvokeCmd 
    ECHO UAC.ShellExecute "!batchPath!", args, "", "runas", 1 >> "%vbsGetPrivileges%"
    goto ExecElevation
    :InvokeCmd
    ECHO args = "/c """ + "!batchPath!" + """ " + args >> "%vbsGetPrivileges%"
    ECHO UAC.ShellExecute "%SystemRoot%\%winSysFolder%\cmd.exe", args, "", "runas", 1 >> "%vbsGetPrivileges%"
    :ExecElevation
    "%SystemRoot%\%winSysFolder%\WScript.exe" "%vbsGetPrivileges%" %*
    exit /B
    :gotPrivileges
    setlocal & cd /d %~dp0
    if '%1'=='ELEV' (del "%vbsGetPrivileges%" 1>nul 2>nul  &  shift /1)
    REM Run shell as admin (example) - put here code as you like
    ECHO %batchName% Arguments: P1=%1 P2=%2 P3=%3 P4=%4 P5=%5 P6=%6 P7=%7 P8=%8 P9=%9
    cmd /k
    

    If you need information on that batch file, run the HTML/JS/CSS Snippet:

    document.getElementsByTagName("data")[0].innerHTML="ElevateBatch, version 4, release
    Required Commands:
    • CLS
    • SETLOCAL
    • SET
    • FOR
    • NET
    • IF
    • ECHO
    • GOTO
    • EXIT
    • DEL
    It auto-elevates the system and if the user presses No, it just doesn't do anything.
    This CANNOT be used to create an Elevated Explorer.";
    data{font-family:arial;text-decoration:none}

提交回复
热议问题