Batch Script to Run as Administrator

后端 未结 12 2081
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 11:18

I\'m writing a client/server checking program but it needs to run as Administrator.

I want this to run silently on my network and users, and I don\'t want the \"Run

12条回答
  •  攒了一身酷
    2020-12-13 11:32

    I made this slight modification to Matt's script to enable it to run from within a single script (just add this to the beginning of any script requiring UAC invocation), but read below the code for an even better solution that I've found on a blog:

    :: ### START UAC SCRIPT ###
    
    if "%2"=="firstrun" exit
    cmd /c "%0" null firstrun
    
    if "%1"=="skipuac" goto skipuacstart
    
    :checkPrivileges
    NET FILE 1>NUL 2>NUL
    if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )
    
    :getPrivileges
    if '%1'=='ELEV' (shift & goto gotPrivileges)
    
    setlocal DisableDelayedExpansion
    set "batchPath=%~0"
    setlocal EnableDelayedExpansion
    ECHO Set UAC = CreateObject^("Shell.Application"^) > "%temp%\OEgetPrivileges.vbs"
    ECHO UAC.ShellExecute "!batchPath!", "ELEV", "", "runas", 1 >> "%temp%\OEgetPrivileges.vbs"
    "%temp%\OEgetPrivileges.vbs"
    exit /B
    
    :gotPrivileges
    
    setlocal & pushd .
    
    cd /d %~dp0
    cmd /c "%0" skipuac firstrun
    cd /d %~dp0
    
    :skipuacstart
    
    if "%2"=="firstrun" exit
    
    :: ### END UAC SCRIPT ###
    
    :: ### START OF YOUR OWN BATCH SCRIPT BELOW THIS LINE ###
    

    My modification uses two file arguments as you can see, which isn't particularly elegant but does the job (and you can always hide them away at the tail end by reserving the first few arguments using dummy placeholders). Additionally, AFAIK Matt's script doesn't support spaces in file paths and this limitation also applies to my modification of this script.

    This issue seems to be inherent in the way VBS handles these paths but on the below link there's an even better VBS-based solution for invoking UAC that runs from within a single script without the need for a workaround like this using file arguments and that also supports spaces in file paths:

    http://pcloadletter.co.uk/2012/12/11/uac-elevation-for-batch-script/

    The script on this link makes slightly different VBS calls as you'll notice, which for some reason circumvents the issue with spaces.

提交回复
热议问题