I am trying to write a batch file for my users to run from their Vista machines with UAC. The file is re-writing their hosts file, so it needs to be run with Administrator permissions. I need to be able to send them an email with a link to the .bat file. The desired behavior is that when they right-click on the file and say Open, they will get one of those UAC dialogs that makes the screen go dark and forces them to answer whether they want to give the application permission to run as administrator. Instead, they are just seeing "Access denied" on the command line window.

有可能采取不同的做法吗?


当前回答

由于我在这个脚本弹出一个新的命令提示符并在无限循环中再次运行时遇到了麻烦(使用Win 7 Pro),我建议您尝试另一种方法:我如何自动提升我的批处理文件,以便它在需要时请求UAC管理员权限?

小心,你必须在脚本的末尾添加这个,就像在编辑中说的那样,这样你就可以在权限提升后回到脚本目录: CD /d %~dp0

其他回答

@echo off和title可以放在下面代码之前:

net session>nul 2>&1
if %errorlevel%==0 goto main
echo CreateObject("Shell.Application").ShellExecute "%~f0", "", "", "runas">"%temp%/elevate.vbs"
"%temp%/elevate.vbs"
del "%temp%/elevate.vbs"
exit

:main
    <code goes here>
exit

如果你不需要担心以下问题,那么很多其他答案都是多余的:

参数 工作目录(cd %~dp0将更改为包含批处理文件的目录)

另一种方法是

在本地创建快捷方式并将其设置为调用管理员权限(属性,高级,以管理员身份运行)

然后

向用户发送快捷方式(或指向快捷方式的链接,而不是指向批处理文件本身的链接)。

这个脚本很有用!只需将其粘贴到bat文件的顶部。如果您想查看脚本的输出,请在批处理文件的底部添加“pause”命令。

更新:这个脚本现在稍微编辑了一下,以支持命令行参数和64位操作系统。

感谢能源@ https://sites.google.com/site/eneerge/scripts/batchgotadmin

@echo off

:: BatchGotAdmin
:-------------------------------------
REM  --> Check for permissions
    IF "%PROCESSOR_ARCHITECTURE%" EQU "amd64" (
>nul 2>&1 "%SYSTEMROOT%\SysWOW64\cacls.exe" "%SYSTEMROOT%\SysWOW64\config\system"
) ELSE (
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
)

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

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params= %*
    echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params:"=""%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B

:gotAdmin
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------    
    <YOUR BATCH SCRIPT HERE>

使用runas命令。但是,我不认为您可以轻松地通过电子邮件发送.bat文件。

另一个PowerShell解决方案…

这不是关于作为管理员运行批处理脚本,而是如何从批处理提升另一个程序…

我有一个批处理文件“包装”的exe。它们具有相同的“根文件名”,但扩展名不同。我能够启动exe作为管理员,并将工作目录设置为一个包含脚本,与以下一行powershell调用:

@powershell "Start-Process -FilePath '%~n0.exe' -WorkingDirectory '%~dp0' -Verb RunAs"

更多信息

还有一大堆额外的Start-Process选项,你也可以申请!查看:https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-6

注意,我使用了@前缀。这相当于一行的@echo off。我在这里使用%~n0来获得批处理脚本的“根名称”,然后连接.exe以指向相邻的二进制文件。%~dp0的使用提供了批处理所在目录的完整路径。当然,-Verb RunAs参数提供抬高。