有一种简单的方法,不需要使用外部工具——它在Windows 7、8、8.1、10和11上运行良好,并且向后兼容(Windows XP没有任何UAC,因此不需要提升——在这种情况下,脚本就会继续)。
看看这段代码(我受到了NIronwolf在线程批处理文件中发布的代码的启发-在Windows 7上“访问被拒绝”?),但我已经改进了它-在我的版本中,没有任何目录创建和删除来检查管理员权限):
::::::::::::::::::::::::::::::::::::::::::::
:: Elevate.cmd - Version 4
:: Automatically check & get admin rights
:: see "https://stackoverflow.com/a/12264592/1016343" for description
::::::::::::::::::::::::::::::::::::::::::::
@echo off
CLS
ECHO.
ECHO =============================
ECHO Running Admin shell
ECHO =============================
:init
setlocal DisableDelayedExpansion
set cmdInvoke=1
set winSysFolder=System32
set "batchPath=%~dpnx0"
rem this works also from cmd shell, other than %~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 **************************************
ECHO Invoking UAC for Privilege Escalation
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)
::::::::::::::::::::::::::::
::START
::::::::::::::::::::::::::::
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
该脚本利用了NET FILE需要管理员权限这一事实,如果没有管理员权限,则返回errorlevel 1。提升是通过创建一个脚本来实现的,该脚本重新启动批处理文件以获得特权。这将导致Windows显示UAC对话框,并要求您输入管理员帐户和密码。
我已经在Windows 7、8、8.1、10、11和Windows XP上测试过了,在所有操作系统上都运行良好。
这样做的好处是,在起始点之后,您可以放置任何需要系统管理员权限的东西,例如,如果您打算为了调试目的重新安装和重新运行Windows服务(假设mypackage。Msi是一个服务安装包):
msiexec /passive /x mypackage.msi
msiexec /passive /i mypackage.msi
net start myservice
如果没有这个特权提升脚本,UAC会三次询问您的管理员用户名和密码——现在您只会在开始时被询问一次,而且是在需要的时候。
如果你的脚本只需要显示一个错误消息,并在没有任何管理员权限时退出,而不是自动提升,这甚至更简单:你可以通过在脚本开头添加以下内容来实现:
@ECHO OFF & CLS & ECHO.
NET FILE 1>NUL 2>NUL & IF ERRORLEVEL 1 (ECHO You must right-click and select &
ECHO "RUN AS ADMINISTRATOR" to run this batch. Exiting... & ECHO. &
PAUSE & EXIT /D)
REM ... proceed here with admin rights ...
这样,用户必须右键单击并选择“以管理员身份运行”。如果检测到管理员权限,脚本将在REM语句之后继续执行,否则将报错退出。如果您不需要PAUSE,只需删除它。
重要:NET文件[…]EXIT /D)必须在同一行。为了更好的可读性,它在这里以多行方式显示!
在一些机器上,我遇到了一些问题,这些问题在上面的新版本中已经解决了。一个是由于不同的双引号处理,另一个问题是由于UAC在Windows 7机器上被禁用(设置为最低级别),因此脚本一次又一次地调用自己。
我现在已经通过剥离路径中的引号并在以后重新添加它们来修复这个问题,并且我还添加了一个额外的参数,当脚本以提升的权限重新启动时添加。
双引号被以下方法删除(详细信息在这里):
setlocal DisableDelayedExpansion
set "batchPath=%~0"
setlocal EnableDelayedExpansion
然后可以使用!batchPath!访问该路径。它不包含任何双引号,因此在脚本后面使用“!batchPath!”是安全的。
这条线
if '%1'=='ELEV' (shift & goto gotPrivileges)
检查脚本是否已经被VBScript脚本调用以提升权限,从而避免无休止的递归。它使用shift删除参数。
更新:
To avoid having to register the .vbs extension in Windows 10, I have replaced the line
"%temp%\OEgetPrivileges.vbs"
by
"%SystemRoot%\System32\WScript.exe" "%temp%\OEgetPrivileges.vbs"
in the script above; also added cd /d %~dp0 as suggested by Stephen (separate answer) and by Tomáš Zato (comment) to set script directory as default.
Now the script honors command line parameters being passed to it. Thanks to jxmallet, TanisDLJ and Peter Mortensen for observations and inspirations.
According to Artjom B.'s hint, I analyzed it and have replaced SHIFT by SHIFT /1, which preserves the file name for the %0 parameter
Added del "%temp%\OEgetPrivileges_%batchName%.vbs" to the :gotPrivileges section to clean up (as mlt suggested). Added %batchName% to avoid impact if you run different batches in parallel. Note that you need to use for to be able to take advantage of the advanced string functions, such as %%~nk, which extracts just the filename.
Optimized script structure, improvements (added variable vbsGetPrivileges which is now referenced everywhere allowing to change the path or name of the file easily, only delete .vbs file if batch needed to be elevated)
In some cases, a different calling syntax was required for elevation. If the script does not work, check the following parameters:
set cmdInvoke=0
set winSysFolder=System32
Either change the 1st parameter to set cmdInvoke=1 and check if that already fixes the issue. It will add cmd.exe to the script performing the elevation.
Or try to change the 2nd parameter to winSysFolder=Sysnative, this might help (but is in most cases not required) on 64 bit systems. (ADBailey has reported this). "Sysnative" is only required for launching 64-bit applications from a 32-bit script host (e.g. a Visual Studio build process, or script invocation from another 32-bit application).
To make it more clear how the parameters are interpreted, I am displaying it now like P1=value1 P2=value2 ... P9=value9. This is especially useful if you need to enclose parameters like paths in double quotes, e.g. "C:\Program Files".
If you want to debug the VBS script, you can add the //X parameter to WScript.exe as first parameter, as suggested here (it is described for CScript.exe, but works for WScript.exe too).
Bugfix provided by MiguelAngelo: batchPath is now returned correctly on cmd shell. This little script test.cmd shows the difference, for those interested in the details (run it in cmd.exe, then run it via double click from Windows Explorer):
@echo off
setlocal
set a="%~0"
set b="%~dpnx0"
if %a% EQU %b% echo running shell execute
if not %a% EQU %b% echo running cmd shell
echo a=%a%, b=%b%
pause
有用的链接:
批处理文件中特殊字符的含义:引号(")、空格(!)、插入号(^)、&号(&)、其他特殊字符