Search code examples
cmdwindows-7windows-vista

How do you run a command as an administrator from the Windows command line?


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.


Solution

  • 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