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

其他回答

我知道这不是OP的解决方案,但是因为我确信这里还有许多其他用例,所以我想分享一下。

我对这些答案中的所有代码示例都有问题,但后来我发现: http://www.robotronic.de/runasspcEn.html

它不仅允许您以管理员身份运行,还可以检查文件以确保它没有被篡改,并安全地存储所需的信息。我承认它不是最明显的工具,但对于我们这些编写代码的人来说,它应该足够简单。

以下是我一直在用的:

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

@echo off 
Net session >nul 2>&1 || (PowerShell start -verb runas '%~0' &exit /b)
Echo Administrative privileges have been got. & pause

上述操作适用于我的Windows 10 1903版

另一个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参数提供抬高。