516

I always work on a non-administrator account on my Windows computer. Sometimes I need to install programs which requires administrator access. As I mostly use the Windows command prompt, is there a Windows command to escalate privileges, similar to the Linux terminal command sudo?

Paul
  • 4,854
ukanth
  • 10,800

19 Answers19

300

The runas command.

runas [{/profile|/noprofile}] [/env] [/netonly] [/smartcard] [/showtrustlevels] [/trustlevel] /user:UserAccountName program

Just run:

runas /noprofile /user:Administrator cmd 

to start a command shell as a administrator

Davy Landman
  • 4,600
149

Elevate - "executes a command with UAC privilege elevation. This is useful for working inside command prompts or with batch files." It's not the same as sudo, it changes the executing user to Administrator, but its syntax is a lot more straightforward to use than runas, and it can keep the current directory, enabling the use of relative paths.

Synopsis:
  elevate [(-c | -k) [-n] [-u]] [-w] command

Options:
  -c  Launches a terminating command processor; equivalent to "cmd /c command".
  -k  Launches a persistent command processor; equivalent to "cmd /k command".
  -n  When using -c or -k, do not pushd the current directory before execution.
  -u  When using -c or -k, use Unicode; equivalent to "cmd /u".
  -w  Waits for termination; equivalent to "start /wait command".

Elevate's purpose isn't to work around or bypass UAC (User Account Control), but to work with it. As long as UAC is enabled there has to be some kind of prompt at some point in the process. If you need to get rid of prompting altogether you have to disable UAC.

The pain point Elevate alleviates is escalating a particular process from a non-privileged shell and then carrying on as normal. Without this you need to start a privileged command prompt with right-click > "Run as Administrator" before attempting the privileged command, which can't be easily scripted.

This works well with "Elevate without prompting" in secpol.msc. Together, they do the same as %wheel ALL=(ALL) NOPASSWD: ALL in sudo

A known limitation is that it does not return the error code from the program it is elevating.

If your muscle memory is stuck on sudo, create an alias using Doskey:
doskey sudo=elevate -w

or batchfile in PATH:
@elevate -w %*

Elevate is 3rd party tool written by Johannes Passing. It's an 11kb download and portable (no install needed): http://code.kliu.org/misc/elevate/

matt wilkie
  • 5,324
68

You can use the runas command which is kind of similar, or you can check out the sudo for Windows project over at SourceForge which adds a sudo command.

The difference is subtle:

Let's say you have two users. Bob is a normal user and James is an administrator.

If you log in as Bob and use "runas james acommand" the command is run as if it was run by James, so it accesses James' user settings and any user changes go into James My Documents & settings folders, etc. So if you are installing an application, say, it will be installed as James, not as Bob.

If on the other hand Bob does "sudo acommand" the command is still run as Bob, but with elevated permissions - just like the Linux sudo command. To prevent any user from being able to sudo you have to define a sudoers user group that contains the list of the normal users that have permission to elevate using sudo. The users still have to provide credentials before elevation.

Sometimes the difference isn't important, sometimes it is, and I find that both commands can be useful.

42

You can also use the Script Elevation PowerToys.

Vinayak
  • 10,885
DDM
  • 549
32

If you are ready to switch to alternative consoles, there is ConEmu (I'm the author). One of its features - the ability to run both elevated and non-elevated tabs in the one ConEmu window. Tabs may be started with different credentials too.

For user comfort, there is batch-file csudo.cmd (which may be easily adopted to bash). Read full description in project's wiki. In brief, when you run some command from existing non-elevated tab, for example

csudo dism /online /enable-feature /featurename:NetFX3 /All /Source:D:\sources\sxs /LimitAccess

ConEmu will starts dism in the new elevated console/tab (with preceding UAC prompt in Vista or Login box in XP).

By default csudo starts new console in a split (may be changes via editing of csudo.cmd contents).

And of course you may rename it to sudo.cmd if you like "classic" sudo word.

sudo in ConEmu/Windows

Maximus
  • 20,835
29

Quick method:

Three steps to add sudo.

  1. Open PowerShell.

  2. Copy the following script (Ctrl+C) and paste it in PowerShell (Alt+Space+E+P):

$script_path="$HOME\Documents\Scripts"; if (!(test-path $script_path)) {New-Item -ItemType directory $script_path} if (!(test-path $profile)) { new-item -path $profile -itemtype file -force }". $script_path\sudo.ps1" | Out-File $profile -append; "function sudo(){if (`$args.Length -eq 1){start-process `$args[0] -verb `"runAs`"} if (`$args.Length -gt 1){start-process `$args[0] -ArgumentList `$args[1..`$args.Length] -verb `"runAs`"}}" | Out-File $script_path\sudo.ps1; powershell
  1. Hit Enter.

It will permanently enable sudo command in PowerShell.

Usage:

sudo <process-name> [param1 [param2 [param3]]]

Examples:

sudo explorer
sudo notepad
sudo powershell
sudo cmd
sudo taskmgr
sudo tasklist
sudo taskkill /IM Skype.exe /PID 8496

Long method for learning:

Note: I mixed the script from both articles to create the aforementioned script. Rather manually pasting the script in notepad I added the Out-File statements to save ps1 and $profile files from the script.

Tip: If you are not a very big fan of UAC popups (like me), save the following in *.reg file and run it:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System]
"ConsentPromptBehaviorAdmin"=dword:00000000
phuclv
  • 30,396
  • 15
  • 136
  • 260
18

If you're doing this on Windows, then in addition to the Run As command as mentioned in a couple of other answers, there are also ways to do this with the mouse.

If you hold down the Shift key as you right-click on most executable files in Windows you should notice a few more advanced options. One of these is the "Run As..." option (I think it's called "Run As Administrator" from Vista onwards).

You can also download a more advanced version of RunAs from Microsoft, called ShellRunAs, this has enhancements over the built-in RunAs command, both in command line and graphical modes, including letting you save account credentials

GAThrawn
  • 4,360
9

I wrote gsudo, a sudo for windows that feels like *nix sudo and has a few killer features:

  • Run within the current console (attached) without breaking tab-key auto-complete. Or add -n to launch in a new window.
  • Handles all scenarios reliably to be used on scripts. (ExitCodes, StdIn/Out/Err Redirection/Capture)
  • Supports Cmd/PowerShell/PowerShell Core
  • Credentials cache: If gsudo is invoked several times within minutes it only shows the UAC pop-up once.

gsudo demo

Usage

gsudo Opens an elevated shell in the current console.

gsudo [options] {command} [arguments] Executes the specified command with elevated permissions.

Most relevant [options]:

  • -n | --new Starts the command in a new console with elevated rights (and returns immediately).
  • -w | --wait Force wait for the process to end (and return the exitcode).
  • -s | --system Run As Local System account ("NT AUTHORITY\SYSTEM").

Installation

  • Using Scoop: scoop install gsudo
  • Using Chocolatey: choco install gsudo
  • Using Winget: winget install gsudo
  • Or check the docs and latest release
6

There is now an official Sudo for Windows. It allows users to run elevated commands directly from unelevated terminal windows.

Sudo is available for Windows 11, version 24H2 or higher (build 26045 and later). If you're on an Insiders build with sudo, you can enable it in the Windows Settings app, on the "Developer Features" page.

Docs: https://learn.microsoft.com/en-us/windows/advanced-settings/sudo/

Source: https://github.com/microsoft/sudo

StayOnTarget
  • 1,494
4

Surun is free, open-source application that allows certain programs to run with administrative rights, without providing a password without changing the user registry or modify environment variables.

When I was using Windows XP this app helps me a lot. Beta works under Windows 7.

diimdeep
  • 822
3

The simplest solution in my view is to leverage powershell to do the work, which is portable and will prompt the user using the UAC.

You can just run this in any shell (cmd or powershell)

powershell Start-Process -verb runAs path-to-your.exe "-all -args -in -quotes"
twall
  • 273
  • 3
  • 10
3

There is a chocolatey package for it with the convenient name sudo. You can install the package with chocolatey using this command:

choco install -y sudo

Then in whatever Windows/MS shell you have to use, you can use sudo as expected.

ypid
  • 373
3

As you've probably discovered, runas will let you run as another user but it cannot do elevation and it doesn't pass current directories, environment variables or long command lines.

Hamilton C shell solves that with a genuine su and sudo. su lets you run a command as another user; sudo (actually an alias to su) lets you run a command elevated. You can also do both, running elevated as a different user. Current directories, environment variables and long command lines are passed by way of a shared memory handshake between su running in the caller's context and a copy of itself running as an interlude with the new credentials that then starts the child. Full disclosure: I'm the author.

Destroy666
  • 12,350
1

A while ago I created wsudo, an open-source sudo-like CLI tool for Windows to run programs or commands with elevated rights, in the context of the current directory. It's freely available as a Chocolatey package.

I use it a lot for things like configuring build agents, admin stuff like sfc /scannow, dism /online /cleanup-image /restorehealth or simply for installing/updating my local Chocolatey packages (e.g., wasudo cup all -y). Use at your own risk.

Installation

choco install wsudo

Chocolatey must be already installed.

Purpose

wsudo is a Linux sudo-like tool for Windows to invoke a program with elevated rights (as Administrator) from a non-admin shell command prompt and keeping its current directory.

This implementation doesn't depend on the legacy Windows Script Host (CScript). Instead, it uses a helper PowerShell 5.1 script that invokes "Start-Process -Wait -Verb runAs ..." cmdlet. Your system most likely already has PowerShell 5.x installed, otherwise you'll be offered to install it as a dependency.

Usage

wsudo runs a program or an inline command with elevated rights in the current directory. Examples:

wsudo .\myAdminScript.bat 
wsudox "del C:\Windows\Temp\*.* && pause"
wasudo cup all -y
wasudox start notepad C:\Windows\System32\drivers\etc\hosts 

I often invoke it from the Windows Run box (Win+R), or by typing wasudo Enter in the Windows Explorer address bar (Alt+D). The latter opens an admin command prompt in the Explorer's current folder.

For more details, visit the GitHub repro.

noseratio
  • 2,963
0

This script does the job:

@echo Set objShell = CreateObject("Shell.Application") > %temp%\sudo.tmp.vbs
@echo args = Right("%*", (Len("%*") - Len("%1"))) >> %temp%\sudo.tmp.vbs
@echo objShell.ShellExecute "%1", args, "", "runas" >> %temp%\sudo.tmp.vbs
@cscript //NoLogo %temp%\sudo.tmp.vbs

Save it as sudo.cmd then add it to your PATH

Note: the runas means in this context "Run as administrator" and not "Run as other user"

Taken from here and slightly edited to remove cscript.exe header from output

Sylveon
  • 190
0

The following vbs script allows to launch a given command with arguments with elevation and mimics the behavior of the original unix sudo command for a limited set of used cases (it will not cache credentials nor it allows to truly execute commands with different credentials). I put it on C:\Windows\System32.

Set objArgs = WScript.Arguments
exe = objArgs(0)
args = ""
IF objArgs.Count >= 2 Then
   args = args & objArgs(1)
End If
For it = 2 to objArgs.Count - 1
   args = args & " " & objArgs(it)
Next
Set objShell = CreateObject( "WScript.Shell")
windir=objShell.ExpandEnvironmentStrings("%WINDIR%")
Set objShellApp = CreateObject("Shell.Application")
objShellApp.ShellExecute exe, args, "", "runas", 1
set objShellApp = nothing

Example use on a command prompt sudo net start service

ceztko
  • 172
  • 1
  • 8
0

A working sudo replacement for Cygwin's mintty terminal would be to place the following script in user's PATH:

$!/bin/bash
cygstart --action=runas mintty -e `which bash` -lc \"$@\"

For me this is the only viable replacement to elevate privileges of programs like vim or cygrunsrv while working in a terminal on Windows.

karafior
  • 137
-1

Another option is TakeCommand's START /ELEVATED … switch.

The noninteractive (TCC-RT) version of the suite is offered for free. The "sudo.btm" batch file would look like

@START "" /ELEVATED %*

which would also support the form sudo /wait <someprogram> /params

AnrDaemon
  • 209
-1

The scoop creator has a simple CLI that works great.

Install with: scoop install sudo

As expected, you need to click UAC dialog to elevate the new process.

$ sudo mkdir 'C:\Program Files\whatever'
Directory: C:\Program Files

Mode LastWriteTime Length Name


d---- 3/11/2024 2:47 PM whatever