70

Is there a way to run a program or command with elevated rights when I am already in a non-elevated command line?

Exactly the same action that would be performed when I click on the program shortcut and select Run as administrator.

The runas command is probably not a solution - it asks for a password, but I just want the UAC dialog.

9 Answers 9

15

It looks like this utility - Hidden Start - will do what you wish if you use the /uac switch. Here's an example command line:

hstart /UAC "notepad.exe"

This will pop up the UAC dialog rather than ask for a password like runas does.

enter image description here

2
  • 2
    Warning: that little utility is 20$. For those with small pocket, use RunAdmin instead :)
    – IceCold
    Jan 27, 2017 at 19:26
  • This doesn't come-up on Windows 10
    – will
    Jun 6, 2017 at 0:32
83

There is a way to do this in PowerShell:

PS> Start-Process powershell -Verb runAs
7
  • 30
    Seems to work fine. From command line, you could do for instance powershell -Command "Start-Process 'C:\program.exe' -Verb runAs"
    – marsze
    Oct 9, 2014 at 11:08
  • 8
    This should be marked as the right/best answer IMO - it works without 3rd party utilities.
    – crimbo
    Oct 21, 2015 at 1:07
  • 5
    Building off of @marsze - Fwiw, arguments in the simplest case go into their own single quoted value, eg powershell -Command "Start-Process 'gvim' 'c:\windows\system32\drivers\etc\hosts' -Verb runAs". Thanks!
    – ruffin
    Jan 11, 2017 at 14:35
  • How can I pipe the output of the elevated command prompt into my currently executing script?
    – wheeler
    Jul 28, 2017 at 23:10
  • @wheeler, I'm almost certain you can't do that, but you can return an exit code: $p = Start-Process powershell -Verb runAs -ArgumentList "-Command ``"& { ``$Host.SetShouldExit(123) }``"" -PassThru; $p.ExitCode
    – Rustam
    Aug 9, 2017 at 11:17
11

Building on Rustam's answer, you can:

  • Create a su.bat batch file somewhere in your default %PATH%, with the following content:
@echo off
setlocal
set cmd=%*
if not defined cmd set cmd=%ComSpec%
powershell iex """start -v runas $Env:cmd"""
  • Add this function to your PowerShell $profile : function su {start -verb runas @args}

Now you can issue su <command> [parameters] in either shell !

3
  • This is nice, but doesn't seem to handle arguments that follow the executable where the arguments contain spaces.
    – Mark
    Jun 11, 2020 at 17:58
  • @Mark Actually fixed this years ago, see my improved answer. Thanks for bringing me back here. ;) Jun 16, 2020 at 22:37
  • Your updated version doesn't work for me, but I had success by using the solution here, and putting start /b %* as the elevated code to run.
    – Mark
    Jun 23, 2020 at 17:01
4

This works for Windows 10, haven't tested with other Windows versions.

A example to open notepad with administrator rights from cmd.exe which starts powershell which asks for the elevated permissions.

C:\>start powershell -command "&{start-process -filepath notepad -verb RunAs}"

This will give you a UAC dialog box (if enabled) with [Yes] [No], or will ask you for the administrator password.

Another example to open the hosts file with notepad would be:

C:\>start powershell -command "&{start-process -filepath notepad 'C:\Windows\System32\drivers\etc\hosts' -verb RunAs}"

More information: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-6

1
  • The arguments to the executable should be a -ArgumentList parameter, not simply additional parameters to start-process.
    – Appleshell
    Oct 12, 2019 at 18:22
4

There is another way to run a process with UAC elevation that works without third-party tools and without having to set the execution policies for PowerShell.

This approach uses the Microsoft HTML Application Host (mshta) to run a VBScript snippet in the form of a single command:

mshta vbscript:Execute("Set UAC = CreateObject(""Shell.Application""):
  UAC.ShellExecute ""SomeProcess.exe"", ""SomeArguments"", """", ""runas"", 1:close")
2
  • +1 Nice point about not "having to set the execution policies for PowerShell"
    – ATorras
    May 21, 2020 at 7:56
  • Neat, clean, native solution. Thank you <3
    – Sam Sirry
    Mar 10, 2022 at 22:45
3

This works for me on all platforms, including Windows 10. My needs are simple, perhaps you can adapt the approach if you need power.

I came up with a small script named, sudo.cmd named for the Linux sudo command. It works well enough it think. I've outlined the requirements, the steps to follow and the script is near the bottom with an example. First a word of warning.

WARNING: The command runs in the windows System directory by default. You will want to cd to somewhere safe first.

requirements:

  • Run command with Administrator a privileged from windows .CMD
    or the cmd-shell.
  • require the normal Windows privilege checks on the command
    • In other words the command will NOT work unless I am already logged in with a privileged account.
  • Execute the command with Admin permission and continue when called inside a script. So wait for the command to complete.
  • Be simple so it will always work
  • Not need to enter a password every time, if I'm already logged in.
    • A better method would be if I can enter password once as does the real sudo command on Linux.

solution:

  1. Create a command script to execute all the arguments passed, sudo.cmd
  2. Create a Windows short-cut to the command script name it: sudo.lnk.
  3. Put the sudo short-cut in your windows PATH so it can be seen.
  4. Edit the short-cut properties, make the Start in: path empty.
  5. Click the [Advanced] button -- Check Run as Administrator
  6. Enable short-cuts in your windows path, use the PATHEXT environment variable, viz.
d:> echo %PATHEXT%
    .lnk;.EXE;.CMD;.BAT;.COM

When you type sudo dir on the command-line Windows will show the

User Account Control

Do you want to allow this app to make changes to this device?

  [YES]  [NO]

Access control pop-up. If you click "[NO]" nothing will happen. Windows will show an "Access is denied." message.

When you click "[YES]" then the directory command runs at an elevated privilege. Of course you probably want something more interesting like stopping or query on a service:

 sudo sc query SDRSVC

SDRSVC is the service name for "Windows Backup service", this shows the following in a separate Cmd window:

  [sudo]

   administrator
  ---------------

  sc query SDRSVC

SERVICE_NAME: SDRSVC
        TYPE               : 10  WIN32_OWN_PROCESS
        STATE              : 4  RUNNING
                                (STOPPABLE, NOT_PAUSABLE, ACCEPTS_SHUTDOWN)
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0

  [done]

Press any key to continue . . .

The sudo.cmd script itself is very basic. As I said my needs are simple. I just want to stop and start services while I deploy code for testing.

sudo.cmd:

 @echo off
 @rem    sudo.cmd
         cd /d %temp%
 @echo.
 @echo.   administrator
 @echo.  ---------------
         cd 
 @echo.
 @rem  _________________________________________________
 @rem      -- Print usage . . .
        @if    [""]      ==["%~1"]   goto USAGE
        @if /i ["--HELP"]==["%~1"]   goto USAGE
 @rem  _________________________________________________
 @rem
 @echo.  %*
 @rem
         %*
 @rem
         set EXIT_STATUS=%ERRORLEVEL%
 @rem  -- -- -- -- --  
 @echo.
 @echo.  [done]
 @rem  ______________________________________________________
 :Exit
 @echo.
 @pause
  exit /b  %EXIT_STATUS%
 @rem  ______________________________________________________
 :USAGE
 @echo.
 @echo  ^Usage:
 @echo.    sudo ^<complete command line^>
 @echo.
 @echo.  Attempts to rune the: ^<complete command line^>
 @echo.  under Administrator priviliges.  Relies on Windows 
 @echo.  prompt for elevated privileges.
 @rem  ______________________________________________________
 @goto Exit

The pause command waits for you to review the results. If you take pause out the administration window closes and you don't know if the command worked or not. The ERRORLEVEL from the command is returned as well.

2

You can set __COMPAT_LAYER=RunAsAdmin. Then the commands will run in a separate elevated cmd.

Example .bat:

rem Run next command elevated to Admin.
set __COMPAT_LAYER=RunAsAdmin
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Group Policy\{35378EAC-683F-11D2-A89A-00C04FBBCFA2}" /t REG_DWORD /v "NoBackgroundPolicy" /d "1"
rem Disable elevation
set __COMPAT_LAYER=
rem continue non elevated
reg add "HKEY_CURRENT_USER\SOFTWARE\Policies\Microsoft\Internet Explorer\Main" /t REG_SZ /v "Start Page" /d "https://www.google.com" /f

All Compatibility Mode options are listed in the MS Application Compatibility Toolkit.

4
  • This batch file is horribly broken. You cannot use ; as a comment delimiter. "Batch files do not recognise the semicolon and will generally cause an error message about a bad command."
    – DavidPostill
    Jan 31, 2017 at 10:57
  • I'm going to upvote @jawa's answer. Using the "__COMPAT_LAYER" environment variable solved the problem for me. Woo-hoo! I think the original BATCH code has been corrected. Feb 5, 2020 at 14:27
  • This can not possibly work. Or if it does write in to HKLM hive, then it is because you are already running your script with an administrator token (you probably started it with Run as administrator" or you are using the built-in administrator account. Indeed, there are 2 reasons it is not possible to do that with a standard user that is in the administrators group. Reason 1: "It also will not work for protected files delivered as part of the OS such as notepad.exe" [or cmd.exe to change compatibility layers] ss64.com/nt/syntax-compatibility.html
    – hymced
    Oct 12, 2020 at 7:50
  • Reason 2: UAC does not allow privilege elevation from command line console to avoid script usage. So again, if it works, you are simply by passing UAC strategies (which this environment variable is intended to) and already have elevated privileges.
    – hymced
    Oct 12, 2020 at 7:55
2

RunAdmin is a small utility (150Kb) that lets you run a program from command line with elevated rights (it will show the UAC). And as opposed to Hidden Start is freeware.

0

Take a look at Start++ - it has this functionality along with a lot of other useful things. To run with the UAC prompt, simply use sudo then your program name at the command line as shown here:

alt text

Here are some other features (you can also add your own):

alt text

alt text

3
  • Looks also good but I already use FARR which has similar functionality as Start++ and more (of course except sudo). Oct 16, 2009 at 8:54
  • 2
    The link says Welcome to: brandontools.com. This Web page is parked FREE. Want to buy brandontools.com?
    – xmojmr
    Jan 5, 2015 at 12:15
  • 1
    as @xmojmr says, that site is dead. If you know a new location (I didn't find one so quickly), you should update the link in the answer.
    – Abel
    Oct 3, 2017 at 16:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .