我希望我的批处理文件只运行提升。如果没有提升,为用户提供一个选项,以提升的方式重新启动批处理。
我正在编写一个批处理文件来设置一个系统变量,将两个文件复制到Program files位置,并启动一个驱动程序安装程序。如果Windows 7/Windows Vista用户(启用了UAC,即使他们是本地管理员)在没有右键单击并选择“以管理员身份运行”的情况下运行它,他们将得到“访问拒绝”,复制这两个文件并写入系统变量。
如果用户实际上是管理员,我想使用一个命令自动重新启动提升的批处理。否则,如果他们不是管理员,我想告诉他们,他们需要管理员权限来运行批处理文件。我使用xcopy复制文件和REG ADD写入系统变量。我正在使用这些命令来处理可能的Windows XP机器。我在这个主题上发现了类似的问题,但没有一个是关于重新启动批处理文件的。
我最近需要一个用户友好的方法,我根据这里和其他地方的贡献者的宝贵见解想出了这个方法。只需将这一行放在.bat脚本的顶部。欢迎您的反馈。
@pushd %~dp0 & fltmc | find "." && (powershell start '%~f0' ' %*' -verb runas 2>nul && exit /b)
无畏:
@pushd %~dp0 ensures a consistant working directory relative to this batch file; supports UNC paths
fltmc a native windows command that outputs an error if run unelevated
| find "." makes the error prettier, and causes nothing to output when elevated
&& ( if we successfully got an error because we're not elevated, do this...
powershell start invoke PowerShell and call the Start-Process cmdlet (start is an alias)
'%~f0' pass in the full path and name of this .bat file. Single quotes allow spaces in the path/file name
' %*' pass in any and all arguments to this .bat file. Funky quoting and escape sequences probably won't work, but simple quoted strings should. The leading space is needed to prevent breaking things if no arguments are present
-verb runas don't just start this process...RunAs Administrator!
2>nul discard PowerShell's unsightly error output if the UAC prompt is canceled/ignored.
&& if we successfully invoked ourself with PowerShell, then...
NOTE: in the event we don't obtain elevation (user cancels UAC), then && allows the .bat to continue running without elevation, such that any commands that require it will fail but others will work just fine. If you want the script to simply exit instead of running unelevated, make this a single ampersand: &
exit /b) exits the initial .bat processing, because we don't need it anymore; we have a new elevated process currently running our .bat. Adding /b allows cmd.exe to remain open if the .bat was started from the command line...it has no effect if the .bat was double-clicked
试试这个:
@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
如果你需要关于批处理文件的信息,运行HTML/JS/CSS代码段:
document.getElementsByTagName(“数据”)[0]。innerHTML="ElevateBatch, version 4, release<br>Required Commands:<ul><li>CLS</li><li>SETLOCAL</li><li>SET</li><li>FOR</li><li>NET</li><li>IF</li><li>ECHO</li><li>GOTO</li><li>EXIT</li><li>DEL</li></ul>它自动提升系统,如果用户按下No,它什么也不做。<br>这个不能用来创建一个提升的资源管理器”;
数据{字体类型:arial;文字修饰:没有}
<数据> < /数据>
我编写了gsudo,一个针对windows的sudo:它在当前控制台中提升(没有上下文切换到新窗口),具有凭据缓存(减少UAC弹出窗口),还提升PowerShell命令。
它允许提升需要管理权限的命令,如果您愿意,也可以提升整个批处理。只要在任何需要升高的东西之前加上gsudo。
使用gsudo提升自身的批处理文件示例:
编辑:新的一行版本,适用于任何windows语言,并避免whoami问题:
net session >nul 2>nul & net session >nul 2>nul || gsudo "%~f0" && exit /b || exit /b
:: This will run as admin ::
替代方案(原版):
@echo off
rem Test if current context is already elevated:
whoami /groups | findstr /b BUILTIN\Administrators | findstr /c:"Enabled group" 1> nul 2>nul && goto :isadministrator
echo You are not admin. (yet)
:: Use gsudo to launch this batch file elevated.
gsudo "%~f0"
goto end
:isadministrator
echo You are admin.
echo (Do admin stuff now).
:end
安装:
通过chocolatey:安装gsudo
或者scoop: scoop install gsudo
或者从github上获取:https://github.com/gerardog/gsudo
查看gsudo的操作:
我是这样做的:
NET SESSION
IF %ERRORLEVEL% NEQ 0 GOTO ELEVATE
GOTO ADMINTASKS
:ELEVATE
CD /d %~dp0
MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 1);close();"
EXIT
:ADMINTASKS
(Do whatever you need to do here)
EXIT
这样做很简单,只使用windows默认命令。
如果你需要重新分发你的批处理文件,这是很好的。
CD /d %~dp0将当前目录设置为文件的当前目录(如果还不是,则与文件所在的驱动器无关,这要归功于/d选项)。
返回当前带扩展名的文件名(如果你不包含扩展名,并且文件夹中有一个同名的exe,它将调用exe)。
这个帖子有这么多回复,我甚至不知道我的回复是否会被看到。
无论如何,我发现这种方法比其他答案上提出的其他解决方案更简单,我希望它能帮助到一些人。