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

前端 未结 8 579
眼角桃花
眼角桃花 2020-11-28 19:14

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, administrati

相关标签:
8条回答
  • 2020-11-28 20:11

    All you have to do is use the runas command to run your program as Administrator (with a caveat).

    runas /user:Administrator "cmdName parameters"
    

    In my case, this was

    runas /user:Administator "cmd.exe /C %CD%\installer.cmd %CD%"
    

    Note that you must use Quotation marks, else the runas command will gobble up the switch option to cmd.

    Also note that the administrative shell (cmd.exe) starts up in the C:\Windows\System32 folder. This isn't what I wanted, but it was easy enough to pass in the current path to my installer, and to reference it using an absolute path.

    Caveat: Enable the admin account

    Using runas this way requires the administrative account to be enabled, which is not the default on Windows 7 or Vista. However, here is a great tutorial on how to enable it, in three different ways:

    I myself enabled it by opening Administrative Tools, Local Security Policy, then navigating to Local Policies\Security Options and changing the value of the Accounts: Administrative Account Status policy to Enabled, which is none of the three ways shown in the link.

    An even easier way:

    C:> net user Administrator /active:yes
    
    0 讨论(0)
  • 2020-11-28 20:12

    Although @amr ali's code was great, I had an instance where my bat file contained > < signs, and it choked on them for some reason.

    I found this instead. Just put it all before your code, and it works perfectly.

    REM  --> Check for permissions
    >nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
    REM --> If error flag set, we do not have admin.
    if '%errorlevel%' NEQ '0' (
        echo Requesting administrative privileges...
        goto UACPrompt
    ) else ( goto gotAdmin )
    :UACPrompt
        echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
        echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
        "%temp%\getadmin.vbs"
        exit /B
    :gotAdmin
        if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
        pushd "%CD%"
        CD /D "%~dp0"
    :--------------------------------------
    
    0 讨论(0)
提交回复
热议问题