Simple method to run a batch as Administrator using javascript

邮差的信 提交于 2019-12-01 21:52:35

问题


I want to derive a simple reliable method to auto elevate a running batch without using extra VBS files or elevated shortcuts, proposed in other threads. Calling the UAC dialog from the batch via javascript ensures the short simple code.

The script below auto elevates a user to Admin rights correctly, when Yes is chosen in the dialog, but the error dialog popups (outside of Cmd window) "Windows cannot find 'test.bat'". Can it be since the path-to-file includes spaces? How to fix the code or suppress this error popup?

@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

回答1:


I fixed the script, and now it runs great. As per my research, this is the simplest reliable way to dynamically give a regular user Administrator privileges for the duration of that Cmd session in a running batch published anywhere.

It doesn't require using functions, hybrid batch & VBS constructs, extra files or elevated shortcuts. It is native to Windows. Users can add their own task code in the :usercode section to run by the batch.

@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


来源:https://stackoverflow.com/questions/38642927/simple-method-to-run-a-batch-as-administrator-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!