150

How do I open a elevated command prompt using command lines on a normal cmd?

For example, I use runas /username:admin cmd but the cmd that was opened does not seem to be elevated! Any solutions?

1

31 Answers 31

220

I ran into the same problem and the only way I was able to open the CMD as administrator from CMD was doing the following:

  1. Open CMD
  2. Write powershell -Command "Start-Process cmd -Verb RunAs" and press Enter
  3. A pop-up window will appear asking to open a CMD as administrator
8
  • 4
    Good answer. I added and edit I used to make it run in one command line! Oct 20, 2015 at 21:28
  • 1
    I created a batch file with this and saved it as admincmd.bat in my windows folder so all I have to do is type "admincmd" hit enter and it opens an admin cmd.(I also added another line to the batch file with "exit" so it closes the non admin cmd window)
    – Tony Brix
    Nov 16, 2015 at 17:11
  • Why not place the cmd (and any parameters) on the end. Having the command is odd from a readability standpoint. Jul 15, 2020 at 18:33
  • Needed this to elevate a prompt running as another user.
    – T2PS
    Sep 10, 2020 at 10:29
  • 1
    @31bit You mean the UAC pop-up? You would have to disable UAC I think (unless there's some loophole I'm not aware of), though for security reasons I STRONGLY urge you to leave UAC enabled. Oct 25, 2022 at 0:13
54

I don't have enough reputation to add a comment to the top answer, but with the power of aliases you can get away with just typing the following:

powershell "start cmd -v runAs"

This is just a shorter version of user3018703 excellent solution:

powershell -Command "Start-Process cmd -Verb RunAs"
2
  • 1
    Note that -v is no longer a shortcut for -Verb, as there is ambiguity between -Verb and -Verbose, so one needs to explicitly spell out -Verb
    – jcaron
    Apr 20, 2021 at 16:44
  • If you need to pass arguments to cmd, such as running a one off task, pass the arguments as an escaped string: powershell "start \"cmd\" \"/C echo \\"hi && pause\\"\" -v runAs" Mar 20 at 1:25
50

Simple way I did after trying other answers here

Method 1: WITHOUT a 3rd party program (I used this)

  1. Create a file called sudo.bat (you can replace sudo with any name you want) with following content powershell.exe -Command "Start-Process cmd \"/k cd /d %cd%\" -Verb RunAs"
  2. Move sudo.bat to a folder in your PATH; if you don't know what that means, just move these files to c:\windows\
  3. Now sudo will work in Run dialog (win+r) or in explorer address bar (this is the best part :))

Method 2: WITH a 3rd party program

  1. Download NirCmd and unzip it.
  2. Create a file called sudo.bat (you can replace sudo with any name you want) with following content nircmdc elevate cmd /k "cd /d %cd%"
  3. Move nircmdc.exe and sudo.bat to a folder in your PATH; if you don't know what that means, just move these files to c:\windows\
  4. Now sudo will work in Run dialog (win+r) or in explorer address bar (this is the best part :))
13
  • 1
    While both solutions work, unfortunately they will result in the UAC dialog showing up on top (z-order-wise) but not getting focused. (Tested on Win10x64 v1607 build14393.447.)
    – Ogmios
    Dec 2, 2016 at 23:57
  • @Ogmios that's rather odd. does the dialog work properly when not initiated like this? I've been very happily using this without such issues. Maybe it's because of some other configuration that you've changed? Dec 3, 2016 at 21:39
  • 2
    I rolled this up into an installable solution: webinstall.dev/sudo
    – coolaj86
    Sep 2, 2020 at 6:35
  • 3
    Please don't use random executables from the web that 'help you elevate privileges'. Bad, bad practice.
    – Jeter-work
    Mar 28, 2021 at 2:33
  • 1
    @Tims This tells powershell to open, and -Command makes it run "Start-Process cmd \"/k cd /d %cd%\" -Verb RunAs" on the first line of the session. This in turn launches an elevated cmd.exe, and /k makes cmd.exe run "cd /d %cd%" on the first line of the session. At some point along the way (I think during the powershell part of the operation), %cd% gets expanded to the working directory you started in, so you don't have to navigate back to it. I'm not sure how robust this is, but it works, somehow. May 28 at 20:57
40

According to documentation, the Windows security model...

does not grant administrative privileges at all times. Even administrators run under standard privileges when they perform non-administrative tasks that do not require elevated privileges.

You have the Create this task with administrative privileges option in the Create new task dialog (Task Manager > File > Run new task), but there is no built-in way to effectively elevate privileges using the command line.

However, there are some third party tools (internally relying on Windows APIs) you can use to elevate privileges from the command line:

NirCmd:

  1. Download it and unzip it.
  2. nircmdc elevate cmd

windosu:

  1. Install it: npm install -g windosu (requires node.js installed)
  2. sudo cmd
7
  • 3
    Thank you, nircmdc elevate route delete 0.0.0.0 mask 0..0.0 192.168.1.1 finally worked. The other runas /user:... ways prompted for a password despite already being an admin (killed batch mode).
    – Marcos
    Aug 31, 2014 at 12:07
  • Thanks for nircmdc elevate cmd
    – tim
    Jun 1, 2016 at 18:32
  • 4
    After intalling nircmd, to have it work like Linux sudo, create a sudo.bat file in your path with this content: nircmd elevate %*. Then you can do, for example, sudo net stop W3SVC
    – Kip
    Nov 14, 2016 at 14:32
  • 1
    i think windosu is by far the simplest and most elegant way of doing this, especially if you are a dev... thanks man. I feel like I am on nix system :D Dec 5, 2017 at 10:55
  • 2
    Please don't use random executables from the web that 'help you elevate privileges'. Bad, bad practice.
    – Jeter-work
    Mar 28, 2021 at 2:34
18

I use nirsoft programs (eg nircmdc) and sysinternals (eg psexec) all the time. They are very helpful.

But if you don't want to, or can't, dl a 3rd party program, here's another way, pure Windows.

Short answer: you can while elevated create a scheduled task with elevated privileges which you can then invoke later while not elevated.

Middle-length answer: while elevated create task with (but I prefer task scheduler GUI):

schtasks /create /sc once /tn cmd_elev /tr cmd /rl highest /st 00:00

Then later, no elevation needed, invoke with

schtasks /run /tn cmd_elev

Long answer: There's a lot of fidgety details; see my blog entry "Start program WITHOUT UAC, useful at system start and in batch files (use task scheduler)"

3
  • @Xalorous This solution does not use any external software
    – spicy.dll
    Sep 23, 2021 at 14:45
  • @Jeter-work schtasks is a built-in windows executable Feb 10, 2022 at 22:47
  • I'm familiar with task scheduler, I think I must have replied to the wrong answer.
    – Jeter-work
    Feb 11, 2022 at 12:24
12

The following as a batch file will open an elevated command prompt with the path set to the same directory as the one from where the batch file was invoked

set OLDDIR=%CD%
powershell -Command "Start-Process cmd -ArgumentList '/K cd %OLDDIR%' -Verb RunAs "
1
  • 2
    The "cd %OLDDIR%" part should be "cd /D %OLDDIR%". Then it works also when the batch file is invoked from a drive other than the default one for cmd (usually C:). Sep 1, 2021 at 14:08
7

While both solutions provided by Dheeraj Bhaskar work, unfortunately they will result in the UAC dialog showing up on top (z-order-wise) but not getting focused (the focused window is the caller cmd/powershell window), thus I either need to grab the mouse and click "yes", or to select the UAC window using Alt+Shift+Tab. (Tested on Win10x64 v1607 build14393.447; UAC = "[...] do not dim [...]".)

The following solution is a bit awkward as it uses two files, but it preserves the correct focus order, so no extra mouse / keyboard actions are required (besides confirming the UAC dialog: Alt+Y).

  1. cmdadm.lnk (shortcut properties / Advanced... / Run as administrator = ON) %SystemRoot%\System32\cmd.exe /k "cd /d"
  2. su.bat @start cmdadm.lnk %cd%

Run with su.

3
  • I unfortunately can't reproduce this. Whenever I use either of my solutions. My UAC prompt is focused and on top May 6, 2019 at 11:37
  • or you could turn off UAC... Just a thought... :) Feb 10, 2022 at 22:51
  • 1
    Turning of UAC is a huge security risk.
    – Ghazali
    Feb 13, 2022 at 14:29
7

Make the batch file save the credentials of the actual administrator account by using the /savecred switch. This will prompt for credentials the first time and then store the encrypted password in credential manager. Then for all subsequent times the batch runs it will run as the full admin but not prompt for credentials because they are stored encrypted in credential manager and the end user is unable to get the password. The following should open an elevated CMD with full administrator privileges and will only prompt for password the first time:

START c:\Windows\System32\runas.exe /user:Administrator /savecred cmd.exe
6

My favorite way of doing this is using PsExec.exe from SysInternals, available at http://technet.microsoft.com/en-us/sysinternals/bb897553

.\psexec.exe -accepteula -h -u "$username" -p "$password" cmd.exe

The "-h" switch is the one doing the magic:

-h If the target system is Vista or higher, has the process run with the account's elevated token, if available.

4
  • 1
    To get this to work you must edit the properties of psexec.exe and on the compatibility tab check "Run as Administrator". Otherwise you will get error : PSEXESVC not installed. But psexec causes issues with the tab key in the cmd.exe. Can't use tab to complete folder names. Aug 27, 2015 at 19:16
  • Not sure on which environment you tried but I didn't need to change the "Run as Administrator" setting (are you trying to run the cmd.exe on a remote machine from yours?). Also no issues with tab key, I can successfully complete files and folders names (at least tested on Win8.1 and Win10, running from both cmd and PowerShell command lines) Aug 27, 2015 at 19:56
  • I'm using Win10 and running it locally. Not sure why it happens to me and not you. I did get nircmd to work and it doesn't cause tab issue. Aug 27, 2015 at 20:46
  • 1
    I also notice that one can't autocomplete with the tab key, but at least this would open elevated cmd prompt in context of another user, which previous methods above did not seem to achieve when I tried. The '-h' flag is great (windows 10), works a treat. Mar 5, 2020 at 20:07
4

I've been using Elevate for awhile now.

It's description - This utility executes a command with UAC privilege elevation. This is useful for working inside command prompts or with batch files.

I copy the bin.x86-64\elevate.exe from the .zip into C:\Program Files\elevate and add that path to my PATH.

Then GitBash I can run something like elevate sc stop W3SVC to turn off the IIS service.

Running the command gives me the UAC dialog, properly focused with keyboard control and upon accepting the dialog I return to my shell.

4
  • Please don't use random executables from the web that 'help you elevate privileges'. Bad, bad practice.
    – Jeter-work
    Mar 28, 2021 at 2:33
  • ...especially without source code.
    – not2qubit
    Dec 1, 2021 at 21:44
  • 1
    @not2qubit It does include source code.
    – gpvos
    Jan 12, 2022 at 17:33
  • @gpvos Correct, it's in the .7zip and there is an .m5d hash included for verification... Jan 12, 2022 at 21:29
4

Dheeraj Bhaskar's method with Powershell has a missing space in it, alt least for the Windows 10 incarnation of Powershell.

The command line inside his sudo.bat should be

powershell.exe -Command "Start-Process cmd \"/k cd /d %cd% \" -Verb RunAs"

Note the extra space after %cd%

;)Frode

3

Similar to some of the other solutions above, I created an elevate batch file which runs an elevated PowerShell window, bypassing the execution policy to enable running everything from simple commands to batch files to complex PowerShell scripts. I recommend sticking it in your C:\Windows\System32 folder for ease of use.

The original elevate command executes its task, captures the output, closes the spawned PowerShell window and then returns, writing out the captured output to the original window.

I created two variants, elevatep and elevatex, which respectively pause and keep the PowerShell window open for more work.

https://github.com/jt-github/elevate

And in case my link ever dies, here's the code for the original elevate batch file:

@Echo Off
REM Executes a command in an elevated PowerShell window and captures/displays output
REM Note that any file paths must be fully qualified!

REM Example: elevate myAdminCommand -myArg1 -myArg2 someValue

if "%1"=="" (
    REM If no command is passed, simply open an elevated PowerShell window.
    PowerShell -Command "& {Start-Process PowerShell.exe -Wait -Verb RunAs}"
) ELSE (
    REM Copy command+arguments (passed as a parameter) into a ps1 file
    REM Start PowerShell with Elevated access (prompting UAC confirmation)
    REM     and run the ps1 file
    REM     then close elevated window when finished
    REM Output captured results

    IF EXIST %temp%\trans.txt del %temp%\trans.txt
    Echo %* ^> %temp%\trans.txt *^>^&1 > %temp%\tmp.ps1
    Echo $error[0] ^| Add-Content %temp%\trans.txt -Encoding Default >> %temp%\tmp.ps1
    PowerShell -Command "& {Start-Process PowerShell.exe -Wait -ArgumentList '-ExecutionPolicy Bypass -File ""%temp%\tmp.ps1""' -Verb RunAs}"
    Type %temp%\trans.txt
)
3

..

@ECHO OFF
SETLOCAL EnableDelayedExpansion EnableExtensions
NET SESSION >nul 2>&1
IF %ERRORLEVEL% NEQ 0 GOTO ELEVATE
GOTO :EOF

:ELEVATE
SET this="%CD%"
SET this=!this:\=\\!

MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('CMD', '/K CD /D \"!this!\"', '', 'runas', 1);close();"
EXIT 1

save this script as "god.cmd" in your system32 or whatever your path is directing to....

if u open a cmd in e:\mypictures\ and type god it will ask you for credentials and put you back to that same place as the administrator...

2
  • 1
    powershell is cool but it needzz modules... im oldscool... just need the system...
    – jOte-
    Feb 9, 2018 at 1:30
  • Does this elevation method/trick also work for long paths/filenames? Or am i supposed to use "%~snx0" or "%~dpsnx0" instead? Oct 1, 2018 at 21:56
3

There seem to be a lot of really creative solutions on this, but I found Stiegler & Gui made the most sense to me. I was looking into how I could do this, but using it in conjunction with my domain admin credential, instead of relying on the local permissions of the "current user".

This is what I came up with:

runas /noprofile /user:DomainName\UserName "powershell start cmd -v runas"

It may seem redundant, but it does prompt for my admin password, and does come up as an elevated command prompt.

1
  • This is what I was looking for... Elevate the user itself as the admin instead of calling the Administrator. But I don't understand what's going on there... cmd -v runas. Why does this thing end up asking for administrative privilege?
    – Zano
    Dec 10, 2021 at 17:07
3

Here is a way to integrate with explorer. It will popup a extra menu item when you right-click in any folder within Windows Explorer:

Windows Explorer Integration

Here are the steps:

  1. Create this key: \HKEY_CLASSES_ROOT\Folder\shell\dosherewithadmin
  2. Change its Default value to whatever you want to appear as the menu item text.
    E.g. "DOS Shell as Admin"
  3. Create another key: \HKEY_CLASSES_ROOT\Folder\shell\dosherewithadmin\command
  4. and change its default value to this:
    powershell.exe -Command "Start-Process -Verb RunAs 'cmd.exe' -Args '/k pushd "%1"'"
  5. Done. Now right-click in any folder and you will see your item there within the other items.

*we use pushd instead of cd to allow it to work in any drive. :-)

2

For fans of Cygwin:

cygstart -a runas cmd
2

The quickest way by far is to:

  1. CTRL+ALT+DELETE
  2. Run TASK MANAGER
  3. Click FILE > Run New Task > type in "cmd" and tick the "Create this task with administrative privileges." box.

Not sure if this helps but this is how I managed to do it. Doesn't help if you need a command to run from batch but hey-ho ... I needed this just because windows explorer is corrupted and needed to fix it.

This is my workaround. Hope this helps someone if not the original poster.

1
  • I never even noticed that checkbox. Excellent!
    – John Dyer
    Apr 15, 2022 at 15:18
2

When a CMD script needs Administrator rights and you know it, add this line to the very top of the script (right below @ECHO OFF):

NET FILE > NUL 2>&1 || POWERSHELL -ex Unrestricted -Command "Start-Process -Verb RunAs -FilePath '%ComSpec%' -ArgumentList '/c \"%~fnx0\" %*'" && EXIT /b

The NET FILE checks for existing Administrator rights. If there are none, PowerShell restarts the current script (with its arguments) in an elevated shell, and the non-elevated script closes.

To allow running scripts -ex Unrestricted is necessary. -Command executes the following string. Start-Process -Verb RunAs runs a process As Administrator: the shell (%ComSpec%, usually C:\Windows\System32\cmd.exe) starting (/c) the current script (\"%~fnx0\") passing its arguments (%*).

Maybe not the exact answer to this question, but it might very well be what people need that end up here.

2
  • Can you please explain, what each of the arguments does?
    – not2qubit
    Nov 24, 2021 at 0:32
  • @not2qubit Sure! Nov 24, 2021 at 11:53
1

A little late for an answer but answering anyway for latecomers like me. I have two approaches. First one is based on little alteration to @Dheeraj Bhaskar's answer and second one is new(that is not mentioned in any answer here).

Approach 1: Create a admin command for windows(just for the sake of flexibility).

@ECHO OFF
powershell -Command "Start-Process %1 -Verb RunAs"

Open notepad -> copy/paste above script -> save it as admin.bat in c:\windows

A lot can be added in the above script to make it better but I've tried to keep it simple and also because I'm not an expert in batch scripting.

Now you can use admin as command to run any other command or application with elevated privileges.

To answer the original question- type admin cmd in standard cmd.

Approach 2:Using runas command. For this we need to enable the built-in Administrator account if not already enabled and set a password. This account is disabled by default on most systems.

When manufacturing PCs, you can use the built-in Administrator account to run programs and apps before a user account is created. Source

Steps to enable Administrator account-

  1. Hit Windows+R and type compmgmt.msc which will open Computer Management window.
  2. Go to System Tools -> Local Users and Groups -> Users
  3. You should see an account with name Administrator here(more info about this account can be found here).
  4. Right click on Administrator and select Properties.
  5. Check Password never expires. Uncheck Account is Disabled and everything else then click OK. This will enable administrator account on your system. Skip if already enabled.
  6. Again Right click on Administrator and click on Set Password(by default it has no password set but for runas command to work we need to set a password). Now windows will show you a life threatening warning which you can accept. OR If you want to play safe then you should login into it after enabling this account and set a password from there.

Now runas command should work- Start a standard cmd and type-

runas /user:administrator cmd

EXTRA: Now we can create something similar to Linux's sudo command. Create a sudo.bat file with following script and save it in c:\windows.

@ECHO OFF
powershell -Command "runas /user:administrator %1"

Now we can do sudo cmd

1

I did this for my smartctl, and it became a portable App. I borrowed it from here.

@echo off

set location=%cd%\bin
powershell -Command "Start-Process cmd -Verb RunAs -ArgumentList { '/k "TITLE Smartctl" & color 07 & pushd "%location%" & prompt $g & echo "Welcome to Smartctl cmd"' }"

prompt $g hides the long leading path.
pushd "%location%" is similar to cd /d "%location%"

  1. Saved as smartctl.cmd
  2. Create a shortcut for smartctl.cmd
  3. Copy the shortcut to C:\Users\#YourName#\AppData\Roaming\Microsoft\Windows\StartMenu\Programs
  4. Click search next to the start menu and input smartctl
  5. Right click Pin to Start
0

Just use the command: runas /noprofile /user:administrator cmd

0

Use:

start, run, cmd, then control+shift+enter

You'll get UAC and then an elevated command shell.

0

Install gsudo tool and use gsudo command. UAC popup appears and eventually command prompt right in the current console window will be elevated:

C:\Users\Someone>net session
System error 5 has occurred.

Access is denied.

C:\Users\Someone>gsudo
C:\Users\Someone# net session
There are no entries in the list.

The tool can be installed using various package managers (Scoop, WinGet, Chocolatey).

1
  • gsudo is a great tool! I want to add that it can also be called via just sudo (which is a shortcut to the actual gsudo.exe). I.e. you can omit the 'g' at the start.
    – Reece
    Aug 1, 2022 at 3:57
0

Create text file named "admin_cmd.reg" with the following content, and run it:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\Background\shell\runas]
@="Cmd here as admin"
"HasLUAShield"=""
"NoWorkingDirectory"=""
"Icon"="imageres.dll,-5324"

[HKEY_CLASSES_ROOT\Directory\Background\shell\runas\command]
@="cmd.exe /s /k pushd \"%V\""

Click on empty space in any folder will give you "Cmd here as admin"

enter image description here

-1

Can use a temporary environment variable to use with an elevated shortcut (

start.cmd

setx valueName_betterSpecificForEachCase %~dp0
"%~dp0ascladm.lnk"

ascladm.lnk (shortcut)

_ properties\advanced\"run as administrator"=yes

(to make path changes you'll need to temporarily create the env.Variable)

_ properties\target="%valueName_betterSpecificForEachCase%\ascladm.cmd"

_ properties\"start in"="%valueName_betterSpecificForEachCase%"

ascladm.cmd

setx valueName_betterSpecificForEachCase=
reg delete HKEY_CURRENT_USER\Environment /F /V valueName_betterSpecificForEachCase
"%~dp0fileName_targetedCmd.cmd"

) (targetedCmd gets executed in elevated cmd window)

Although it is 3 files ,you can place everything (including targetedCmd) in some subfolder (do not forget to add the folderName to the patches) and rename "start.cmd" to targeted's one name

For me it looks like most native way of doing this ,whilst cmd doesn't have the needed command

1
  • i have read all of above solutions and understood them. i do not understand steps of yours. i am choosing solution with best pros and cons. Oct 14, 2018 at 6:43
-1

You can use the following syntax, I had the same question and did not think a script should be needed.

runas /profile /user:domain\username cmd

This worked for me, it may be different on your network.

-2

I did it easily by using this following command in cmd

runas /netonly /user:Administrator\Administrator cmd

after typing this command, you have to enter your Administrator password(if you don't know your Administrator password leave it blank and press Enter or type something, worked for me)..

2
  • did not help me Oct 14, 2018 at 6:39
  • @DzmitryLahoda can you brief me the error that you got? Oct 28, 2019 at 11:35
-2

Press the Windows + X key and you can now select the Powershell or Command Prompt with admin rights. Works if you are the admin. The function can be unusable if the system is not yours.

-3

I've created this tool in .Net 4.8 ExecElevated.exe, 13KB (VS 2022 source project) it will execute an application with an elevated token (in admin mode). But you will get an UAC dialog to confirm! (maybe not if UAC has been disabled, haven't tested it).

And the account calling the tool must also have admin. rights of course.

Example of use:

ExecuteElevated.exe "C:\Utility\regjump.exe HKCU\Software\Classes\.pdf"
7
  • 3
    I just love the answers with "This might work haven't tested yet", and of course the one with "not sure".... Apr 12, 2015 at 15:51
  • 1
    link is broken. Oct 14, 2018 at 6:39
  • Link reestablished, sorry for that
    – MrCalvin
    Oct 18, 2018 at 22:59
  • 2
    Please don't use random executables from the web that 'help you elevate privileges'. Bad, bad practice.
    – Jeter-work
    Mar 28, 2021 at 2:30
  • Yeah, at least post the source code to these things.
    – not2qubit
    Dec 1, 2021 at 21:34
-5

I used runas /user:domainuser@domain cmd which opened an elevated prompt successfully.

1
  • It requires the credentials of another user. If you're already Administrator and want to run with elevated privileges like when you right click an application and choose run as administrator and no password is requested, just a confirmation dialog, then you need something else. I came here searching for that answer but doesn't seem to be here. Nov 20, 2014 at 8:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.