如何从Windows命令行以管理员身份运行命令?

问题描述:

我有一个小脚本,在Windows上为我管理的bazaar存储库执行构建和安装过程。我试图从 Windows Shell(cmd.exe)中的 提升的管理权限运行脚本 - 就像我右键单击它并选择以管理员身份运行

I have a small script that performs the build and install process on Windows for a bazaar repository I'm managing. I'm trying to run the script with elevated, administrative privileges from within the Windows Shell (cmd.exe)--just as if I'd right-clicked it and chosen Run as Administrator, but without using any method that requires use of the Graphical Interface.

我没有看到任何回答这在网上或这里stackoverflow,但没有使用任何需要使用图形界面的方法。但经过一个小时的搜索后,我设法拼写了一个答案,我已在下面发布。

I don't see any answer to this on the net or here on stackoverflow, but after an hour or so of searching, I managed to piece together an answer, which I have posted below. Feel free to provide alternate or expanded answers, however.

批处理/ WSH混合可以调用ShellExecute来显示UAC海拔对话框...

A batch/WSH hybrid is able to call ShellExecute to display the UAC elevation dialog...

@if (1==1) @if(1==0) @ELSE
@echo off&SETLOCAL ENABLEEXTENSIONS
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"||(
    cscript //E:JScript //nologo "%~f0"
    @goto :EOF
)
echo.Performing admin tasks...
REM call foo.exe
@goto :EOF
@end @ELSE
ShA=new ActiveXObject("Shell.Application")
ShA.ShellExecute("cmd.exe","/c \""+WScript.ScriptFullName+"\"","","runas",5);
@end