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

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

    Matt has a great answer, but it strips away any arguments passed to the script. Here is my modification that keeps arguments. I also incorporated Stephen's fix for the working directory problem in Windows 8.

    @ECHO OFF
    setlocal EnableDelayedExpansion
    
    ::net file to test privileges, 1>NUL redirects output, 2>NUL redirects errors
    NET FILE 1>NUL 2>NUL
    if '%errorlevel%' == '0' ( goto START ) else ( goto getPrivileges ) 
    
    :getPrivileges
    if '%1'=='ELEV' ( goto START )
    
    set "batchPath=%~f0"
    set "batchArgs=ELEV"
    
    ::Add quotes to the batch path, if needed
    set "script=%0"
    set script=%script:"=%
    IF '%0'=='!script!' ( GOTO PathQuotesDone )
        set "batchPath=""%batchPath%"""
    :PathQuotesDone
    
    ::Add quotes to the arguments, if needed.
    :ArgLoop
    IF '%1'=='' ( GOTO EndArgLoop ) else ( GOTO AddArg )
        :AddArg
        set "arg=%1"
        set arg=%arg:"=%
        IF '%1'=='!arg!' ( GOTO NoQuotes )
            set "batchArgs=%batchArgs% "%1""
            GOTO QuotesDone
            :NoQuotes
            set "batchArgs=%batchArgs% %1"
        :QuotesDone
        shift
        GOTO ArgLoop
    :EndArgLoop
    
    ::Create and run the vb script to elevate the batch file
    ECHO Set UAC = CreateObject^("Shell.Application"^) > "%temp%\OEgetPrivileges.vbs"
    ECHO UAC.ShellExecute "cmd", "/c ""!batchPath! !batchArgs!""", "", "runas", 1 >> "%temp%\OEgetPrivileges.vbs"
    "%temp%\OEgetPrivileges.vbs" 
    exit /B
    
    :START
    ::Remove the elevation tag and set the correct working directory
    IF '%1'=='ELEV' ( shift /1 )
    cd /d %~dp0
    
    ::Do your adminy thing here...
    

提交回复
热议问题