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.

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


当前回答

以下是我一直在用的:

@echo off
if not "%1"=="am_admin" (
    powershell -Command "Start-Process -Verb RunAs -FilePath '%0' -ArgumentList 'am_admin'"
    exit /b
)

echo main code here
pause

注:

Start-Process的-Verb RunAs标志是启用管理提升的标志。 只在windows 7和10上测试过,你可能得把引号弄乱 目前不支持传递参数,但你可以向-ArgumentList中添加更多的东西。注意-ArgumentList接受单个字符串或字符串数组。

其他回答

@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将更改为包含批处理文件的目录)

另一种方法是

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

然后

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

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

使用mshta提示管理员权限:

@echo off
net session >nul 2>&1 && goto :admintasks
MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 1);close();"
exit /b
:admintasks
rem ADMIN TASKS HERE

或者,使用powershell:

powershell -c Start-Process "%~nx0" -Verb runas

你不能从批处理文件中请求管理权限,但是你可以在%temp%中编写一个windows脚本主机脚本并运行它(它反过来以管理员身份执行你的批处理)。使用“runas”作为动词的应用程序对象