[windows] How to open an elevated cmd using command line for Windows?

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?

This question is related to windows cmd command

The answer is


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.


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 "

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.


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

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.


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.


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)"


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 :))

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

I'm not sure the tool ExecElevated.exe (13KB) will do the job....but it might. Or at least be useful for others with similar needs who came to this page as I did (but I didn't find the solution so I ended up creating the tool myself in .Net).

It will execute an application with 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"

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


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


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
)

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


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.


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

For fans of Cygwin:

cygstart -a runas cmd

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. Ex "DOS Shell as Admin"
  3. Create this another key: \HKEY_CLASSES_ROOT\Folder\shell\dosherewithadmin\command
  4. Change its default value to this, ipsis litteris: powershell.exe -Command "Start-Process -Verb RunAs 'cmd.exe' -Args '/k pushd "%1"'"
  5. It's done. Now right-click in any folder and you will see your item there within the other items.

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


There are several ways to open an elevated cmd, but only your method works from the standard command prompt. You just need to put user not username:

runas /user:machinename\adminuser cmd

See relevant help from Microsoft community.


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


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"

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)..


..

@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...


Examples related to windows

"Permission Denied" trying to run Python on Windows 10 A fatal error occurred while creating a TLS client credential. The internal error state is 10013 How to install OpenJDK 11 on Windows? I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? git clone: Authentication failed for <URL> How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" XCOPY: Overwrite all without prompt in BATCH Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory how to open Jupyter notebook in chrome on windows Tensorflow import error: No module named 'tensorflow'

Examples related to cmd

'ls' is not recognized as an internal or external command, operable program or batch file '' is not recognized as an internal or external command, operable program or batch file XCOPY: Overwrite all without prompt in BATCH VSCode Change Default Terminal How to install pandas from pip on windows cmd? 'ls' in CMD on Windows is not recognized Command to run a .bat file VMware Workstation and Device/Credential Guard are not compatible How do I kill the process currently using a port on localhost in Windows? how to run python files in windows command prompt?

Examples related to command

'ls' is not recognized as an internal or external command, operable program or batch file Command to run a .bat file how to run python files in windows command prompt? Run a command shell in jenkins How to recover the deleted files using "rm -R" command in linux server? Split text file into smaller multiple text file using command line ansible : how to pass multiple commands Jmeter - Run .jmx file through command line and get the summary report in a excel cocoapods - 'pod install' takes forever Daemon not running. Starting it now on port 5037