使用 javascript 以管理员身份 运行 批处理的简单方法

Simple method to run a batch as Administrator using javascript

我想推导一种简单可靠的方法来自动提升 运行 批次,而无需使用其他线程中提出的额外 VBS 文件或提升的快捷方式。通过 javascript 从批处理中调用 UAC 对话框确保了简短的代码。

当在对话框中选择是时,下面的脚本会自动将用户正确提升到管理员权限,但会弹出错误对话框(在 Cmd 之外 window)“Windows 找不到 'test.bat'”。可能是因为文件路径包含空格吗?如何修复代码或抑制此错误弹出窗口?

@echo off
:: test admin rights
>nul 2>&1 net file
echo '%errorlevel%'
MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute("%~nx0", '', '', 'runas', 1);close();"
:: test admin rights
>nul 2>&1 net file
echo '%errorlevel%'
if !errorlevel! equ 0 echo Hello >%temp%\tst.txt
exit /b

我修复了脚本,现在 运行 非常棒。根据我的研究,这是在任何地方发布的 运行ning 批处理中,在该 Cmd 会话期间动态授予普通用户管理员权限的最简单可靠的方法。

它不需要使用函数、混合批处理和 VBS 构造、额外文件或提升的快捷方式。它原产于 Windows。用户可以在:usercode部分批量添加自己的任务代码到运行

@echo off
setlocal EnableDelayedExpansion
:: test and acquire admin rights
cd /d %~dp0 & echo/
if not "%1"=="UAC" (
    >nul 2>&1 net file && echo Got admin rights || (echo No admin rights & ^
MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute("%~snx0", 'UAC', '', 'runas', 1);close();"))
:: re-test admin rights
echo/ & >nul 2>&1 net file && (echo Got admin rights & echo/) || (echo No admin rights. Exiting... & goto :end)

:usercode
:: add your code here
echo Performing admin tasks
echo Hello >C:\test.txt

:end
timeout /t 5 >nul
exit /b