How do I execute a batch file in administrator mode [closed]

房东的猫 提交于 2019-12-04 20:01:50

If you want your batch script to ask for elevation if needed, this page might help you. I adapted it to use in a batch script I serve from the web like this:

REM  --> Check for permissions
"%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system">nul 2>NUL

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    if exist "%temp%\getadmin.vbs" (
        del "%temp%\getadmin.vbs"
        echo Failed to acquire elevated privilege.  Try saving this script and running it from your Desktop.
        echo;
        echo Press any key to exit.
        pause>NUL
        goto :EOF
    )
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    echo UAC.ShellExecute "%~s0", "%*", "", "runas", 1 >> "%temp%\getadmin.vbs"

    cscript /nologo "%temp%\getadmin.vbs"
    goto :EOF

:gotAdmin
    if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
:--------------------------------------

:: The rest of the script goes here...

Regarding the "Try saving this script" message, if the user attempts to open the batch script directly from the web browser, browser security might block the elevation. I had to include that to remind my users to save the script first, then run it independently outside the web browser.

Anyway, salt to taste.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!