Как правило, большинство системных инструментов требует наличия у запускающего их пользователя административных привилегий. Таким образом, чтобы иметь возможность выполнения операций по управлению системой, администратор должен зарегистрироваться в системе под учетной записью, обладающей соответствующими правами. Однако правила безопасности требуют от администратора не пользоваться для постоянной работы в системе подобными учетными записями.
Команда RunAs позволяет администратору выполнять всю работу по управлению системой, зарегистрировавшись в ней с использованием учетной записи рядового пользователя с весьма ограниченными правами. При помощи данной команды администратор может запускать любые утилиты от имени «уполномоченного» пользователя (при этом может быть задействована либо учетная запись администратора, либо учетная запись пользователя, обладающего необходимыми правами).
Внимание
Для работы команды RunAs необходимо, чтобы была запущена служба Secondary Logon. Поэтому, в случае возникновения проблем с работой данной команды необходимо в первую очередь убедиться в том, что указанная служба действительно запущена. Чтобы убедиться в этом, можно использовать оснастку Services.
Команда RunAs может быть использована для установки и проверки пользовательских разрешений на доступ к файлам или объектам Active Directory. Для задания пользователю разрешений необходимо запустить соответствующую утилиту с административными привилегиями. Одновременно можно запустить требуемое приложение в контексте полномочий рассматриваемого пользователя и проверить результирующие разрешения. Таким образом, задача может быть решена (и, что главное, проверена) без необходимости повторных регистрации в системе под разными учетными записями.
Команда RunAs может использоваться в двух режимах.
- Запуск утилит из контекстного меню. Запуск утилиты или оснастки с необходимыми полномочиями происходит путем использования контекстного меню. Администратор выбирает соответствующий пункт меню и предоставляет информацию о своих полномочиях. Данный режим идеально подходит для запуска графических утилит.
- Запуск утилит из командной строки. В режиме командной строки администратор вводит команду со всеми необходимыми параметрами. Этот режим может использоваться для запуска утилит командной строки. Другим преимуществом этого режима является возможность отображения сведений о результатах процесса запуска (в том числе информация о возникающих ошибках).
Рассмотрим особенности использования каждого из режимов более подробно.
Запуск утилит из контекстного меню
Администратор может запускать утилиты и оснастки любым способом — из главного меню, с рабочего стола, из программы Windows Explorer. При этом механизм административных утилит не требует, чтобы утилита запускалась на контроллере домена. Более того, чтобы не снижать производительность контроллера домена, рекомендуется использовать для управления системой специально выделенную рабочую станцию. Чтобы иметь на этой рабочей станции возможность осуществлять управление сетью, администратор должен предварительно установить на нее необходимые административные утилиты (как из набора Windows Server 2003 Administrative Pack, так и из вспомогательных пакетов Windows Server 2003 Support Tools и Resource Kit).
В случае если речь идет об установке определенных утилит для пользователей, которым делегированы полномочия на выполнение определенных операций, нет необходимости устанавливать весь пакет утилит. Можно установить на рабочую станцию только одну или несколько утилит из пакета Windows Server 2003 Administrative Tools. Для этого следует скопировать необходимые оснастки (файлы с расширением msc) и связанные с ними DLL-библиотеки из папки %SystemRoot%system32 контроллера домена в любую папку на рабочей станции. Перейдя в указанную папку на рабочей станции, требуется зарегистрировать скопированные DLL-библиотеки. Для этого в режиме командной строки необходимо выполнить: regsvr32 <имя_DLL-библиотеки>
В табл. 10.1 приведены имена DLL-библиотек для некоторых, наиболее важных административных утилит.
Таблица 10.1. DDL-библиотеки, необходимые для работы некоторых административных утилит
Оснастка | Имя файла оснастки | Имя DLL-библиотеки |
Active Directory Domain and Trusts | domain, msc | domadmin.dll |
Active Directory Users and Computers | dsa.msc | dsadmin.dll |
Active Directory Sites and Services | dssite.msc | dsadmin.dll |
Active Directory Schema | — | schmmgmt.dll |
Примечание
Оснастка Active Directory Schema не инсталлируется автоматически. После того как файл schmmgmt.dll скопирован на рабочую станцию и зарегистрирован, пользователь должен добавить оснастку в управляющую консоль (ММС) и сохранить под некоторым именем.
Чтобы при помощи команды RunAs запустить утилиту с необходимыми полномочиями, вызовите контекстное меню утилиты, щелкнув по ее имени или пиктограмме правой кнопкой мыши. В меню выберите пункт Run as (Запустить как). В открывшемся окне (рис. 10.4) надо определить способ запуска утилиты — либо с полномочиями текущего пользователя (переключатель Current user), либо с полномочиями другого пользователя (переключатель The following user). В последнем случае необходимо предоставить сведения об имени учетной записи и сопоставленном ей пароле. Следует также указывать имя домена, к которому принадлежит учетная запись.
Рис. 10.4. Запуск программы с полномочиями другого пользователя
Примечание
Запуская утилиту в контексте текущего пользователя, можно защитить систему (прежде всего данные) от несанкционированных действий со стороны запущенного приложения. Подобные действия могут иметь место в случае, если приложение заражено компьютерным вирусом или является своего рода «троянским конем». Для этого необходимо установить флажок Run this program with restricted access.
В контекстном меню отдельных утилит имеется пункт Author, выбор которого позволяет запустить оснастку в авторском режиме. Авторский режим дает возможность модифицировать параметры оснастки.
Если утилита должна всегда запускаться в рамках полномочий другого пользователя, необходимо соответствующим образом сконфигурировать ярлык утилиты. Вызвав окно свойств ярлыка утилиты, на вкладке Shortcut (Ярлык) нужно щелкнуть по кнопке Advanced (Дополнительно). В открывшемся окне установите флажок Run with different credentials (Запускать с другими полномочиями).
Запуск утилит из командной строки
При-помощи команды RunAs можно запускать из командной строки любые исполняемые файлы (имеющие расширение exe, com, cmd, bat, msc), ярлыки (lnk), а также элементы панели управления (cpl).
Внимание
Существуют приложения и элементы, с которыми команда RunAs не может быть использована. Например, программа Windows Explorer, папка Printers и элементы рабочего стола.
Для запуска из командной строки утилит из пакета Windows Server 2003 Administrative Tools необходимо знать имена оснасток. В табл. 10.2 приводятся имена оснасток для наиболее часто используемых утилит из этого пакета.
Таблица 10.2. Имена оснасток для некоторых утилит пакета Windows Server 2003 Administrative Tools
Утилита | Имя оснастки |
Active Directory Domains and Trusts | domain. msc |
Active Directory Schema | должна быть создана администратором вручную |
Active Directory Sites and Services | dssite.msc |
Active Directory Users and Computers | dsa.msc |
Computer Management | compmgmt.msc |
Distributed File System | dfsgui.msc |
DNS | dnsmgmt.msc |
Domain Controller Security Settings | dcpol.msc |
Domain Security Settings | dompol.msc |
Group Policy | gpedit.msc |
Local Security Settings | secpol.msc |
Routing and Remote Access | rrasmgmt.msc |
Services | services, msc |
Device Manager* | devmgmt.msc |
Disk Management* | diskmgmt.msc |
Local Users and Groups* | lusrmgr.msc |
Shared Folders* | fsmgmt.msc |
*Оснастки, не отображаемые в меню Administrative Tools. Однако их можно найти в папке %SystemRoot%system32
Команда RunAs имеет следующий формат:
runas [ [/noprofile | /profile] [/env] [/savecred | /netonly]]
/user:<имя_пользователя> приложение
Ключевые слова имеют следующий смысл:
- /noprofile — в процессе запуска утилиты не будет осуществляться загрузка профиля пользователя. Благодаря этому приложения запускаются быстрее. Однако приложения, использующие информацию, размещенную в профиле пользователя, могут не работать;
- /profile — загружается профиль пользователя. Данный режим выбирается по умолчанию;
- /env — использовать текущее окружение, вместо того, чтобы создавать окружение, характерное для конкретного пользователя;
- /savecred — использовать полномочия предыдущего пользователя;
- /netonly — использовать полномочия исключительно для доступа к удаленным ресурсам;
- /user — учетная запись пользователя.
Ниже приводится пример запуска оснастки Active Directory Users and Computers с полномочиями пользователя lex: c:runas /user:lex@khsu.ru «mmc domain.msc»
В приведенном примере утилита запускается для управления доменом, к которому принадлежит текущий пользователь. Если необходимо запустить утилиту с полномочиями пользователя, принадлежащего к другому домену, используется другой формат команды. Ниже приводится пример запуска оснастки Active Directory Users and Computers с полномочиями пользователя kaizer, принадлежащего к домену kit.khsu.ru (NetBIOS-имя домена — KIT): c:runas /netonly /user:KITkaizer «mmc domain.msc»
В приведенном примере используется формат NetBIOS для предоставления информации о домене, к которому принадлежит пользователь (домен пользователь). Однако допускается и использование основных имен пользователя (UPN).
30.06.2009 —
Posted by |
ms windows server 2003
Sorry, the comment form is closed at this time.
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:Administrator "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:WindowsSystem32 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 PoliciesSecurity 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 to accomplish this:
C:> net user Administrator /active:yes
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:
- Open CMD
- Write
powershell -Command "Start-Process cmd -Verb RunAs"
and press Enter - A pop-up window will appear asking to open a CMD as administrator
Felix Dombek
13.3k17 gold badges78 silver badges127 bronze badges
answered Aug 26, 2015 at 1:05
GuiGui
2,2271 gold badge11 silver badges3 bronze badges
6
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"
answered Nov 10, 2018 at 9:29
StieglerStiegler
6896 silver badges8 bronze badges
1
Simple way I did after trying other answers here
Method 1: WITHOUT a 3rd party program (I used this)
- Create a file called
sudo.bat
(you can replacesudo
with any name you want) with following content
powershell.exe -Command "Start-Process cmd "/k cd /d %cd%" -Verb RunAs"
- Move
sudo.bat
to a folder in yourPATH
; if you don’t know what that means, just move these files toc:windows
- 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
- Download NirCmd and unzip it.
- Create a file called
sudo.bat
(you can replacesudo
with any name you want) with following content
nircmdc elevate cmd /k "cd /d %cd%"
- Move
nircmdc.exe
andsudo.bat
to a folder in yourPATH
; if you don’t know what that means, just move these files toc:windows
- Now
sudo
will work in Run dialog (win+r) or in explorer address bar (this is the best part :))
answered Oct 29, 2016 at 16:40
Dheeraj BhaskarDheeraj Bhaskar
18.4k9 gold badges63 silver badges66 bronze badges
12
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:
- Download it and unzip it.
nircmdc elevate cmd
windosu:
- Install it:
npm install -g windosu
(requires node.js installed) sudo cmd
answered Mar 21, 2014 at 15:28
Ricardo StuvenRicardo Stuven
4,6762 gold badges35 silver badges36 bronze badges
7
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)»
bluish
25.6k27 gold badges119 silver badges177 bronze badges
answered Feb 19, 2015 at 7:59
3
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 "
answered Apr 14, 2017 at 0:25
statlerstatler
1,2741 gold badge15 silver badges24 bronze badges
1
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).
- cmdadm.lnk (shortcut properties / Advanced… / Run as administrator = ON)
%SystemRoot%System32cmd.exe /k "cd /d"
- su.bat
@start cmdadm.lnk %cd%
Run with su
.
answered Dec 3, 2016 at 0:18
OgmiosOgmios
6487 silver badges12 bronze badges
3
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.
answered Sep 7, 2014 at 14:11
David RodriguezDavid Rodriguez
2,3921 gold badge17 silver badges15 bronze badges
4
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:WindowsSystem32runas.exe /user:Administrator /savecred cmd.exe
bluish
25.6k27 gold badges119 silver badges177 bronze badges
answered May 17, 2018 at 18:32
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-64elevate.exe
from the .zip
into C:Program Fileselevate
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.
answered Jun 11, 2017 at 16:33
seangwrightseangwright
16.7k6 gold badges41 silver badges54 bronze badges
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
answered May 14, 2019 at 9:19
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:WindowsSystem32 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
)
answered Mar 7, 2017 at 14:38
..
@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…
answered Feb 9, 2018 at 0:40
jOte-jOte-
514 bronze badges
2
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:DomainNameUserName "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.
answered Oct 7, 2021 at 14:18
1
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:
Here are the steps:
- Create this key:
HKEY_CLASSES_ROOTFoldershelldosherewithadmin
- Change its Default value to whatever you want to appear as the menu item text.
E.g. «DOS Shell as Admin« - Create another key:
HKEY_CLASSES_ROOTFoldershelldosherewithadmincommand
- and change its default value to this:
powershell.exe -Command "Start-Process -Verb RunAs 'cmd.exe' -Args '/k pushd "%1"'"
- 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.
not2qubit
13.3k8 gold badges89 silver badges122 bronze badges
answered Jul 18, 2020 at 21:11
rribasrribas
4151 gold badge6 silver badges6 bronze badges
For fans of Cygwin:
cygstart -a runas cmd
answered Nov 15, 2020 at 12:22
gavenkoagavenkoa
43.6k17 gold badges243 silver badges295 bronze badges
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:WindowsSystem32cmd.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.
answered Sep 21, 2021 at 10:15
Michel de RuiterMichel de Ruiter
6,7035 gold badges50 silver badges70 bronze badges
2
The quickest way by far is to:
CTRL+ALT+DELETE
- Run TASK MANAGER
- 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.
tomerpacific
4,38612 gold badges33 silver badges51 bronze badges
answered Aug 16, 2021 at 10:30
GarethGareth
591 gold badge1 silver badge6 bronze badges
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-
- Hit Windows+R and type
compmgmt.msc
which will open Computer Management window. - Go to System Tools -> Local Users and Groups -> Users
- You should see an account with name Administrator here(more info about this account can be found here).
- Right click on Administrator and select Properties.
- 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.
- 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
answered Dec 1, 2021 at 16:32
avmavm
3773 silver badges15 bronze badges
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%"
- Saved as
smartctl.cmd
- Create a shortcut for
smartctl.cmd
- Copy the shortcut to
C:Users#YourName#AppDataRoamingMicrosoftWindowsStartMenuPrograms
- Click search next to the start menu and input
smartctl
- Right click
Pin to Start
answered Dec 3, 2021 at 6:28
Just use the command:
runas /noprofile /user:administrator cmd
answered Jan 8, 2020 at 9:32
Use:
start
, run
, cmd
, then control+shift+enter
You’ll get UAC and then an elevated command shell.
answered Mar 28, 2021 at 2:36
Jeter-workJeter-work
7577 silver badges22 bronze badges
Install gsudo tool and use gsudo
command. UAC popup appears and eventually command prompt right in the current console window will be elevated:
C:UsersSomeone>net session
System error 5 has occurred.
Access is denied.
C:UsersSomeone>gsudo
C:UsersSomeone# net session
There are no entries in the list.
The tool can be installed using various package managers (Scoop, WinGet, Chocolatey).
answered Jul 16, 2022 at 20:51
Ilya SerbisIlya Serbis
20.5k6 gold badges81 silver badges72 bronze badges
1
Can use a temporary environment variable to use with an elevated shortcut (
start.cmd
setx valueName_betterSpecificForEachCase %~dp0
"%~dp0ascladm.lnk"
ascladm.lnk (shortcut)
_ propertiesadvanced"run as administrator"=yes
(to make path changes you’ll need to temporarily create the env.Variable
)
_ propertiestarget="%valueName_betterSpecificForEachCase%ascladm.cmd"
_ properties"start in"="%valueName_betterSpecificForEachCase%"
ascladm.cmd
setx valueName_betterSpecificForEachCase=
reg delete HKEY_CURRENT_USEREnvironment /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
Jee Mok
5,8498 gold badges46 silver badges75 bronze badges
answered Jul 25, 2018 at 23:28
iliailia
291 silver badge5 bronze badges
1
You can use the following syntax, I had the same question and did not think a script should be needed.
runas /profile /user:domainusername cmd
This worked for me, it may be different on your network.
answered Nov 29, 2019 at 15:28
I did it easily by using this following command in cmd
runas /netonly /user:AdministratorAdministrator 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)..
answered Aug 16, 2018 at 7:18
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.
Trooper Z
1,58013 silver badges31 bronze badges
answered Feb 25, 2019 at 14:11
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:Utilityregjump.exe HKCUSoftwareClasses.pdf"
answered Nov 14, 2014 at 23:55
MrCalvinMrCalvin
1,5531 gold badge16 silver badges23 bronze badges
7
I used runas /user:domainuser@domain cmd
which opened an elevated prompt successfully.
answered Mar 10, 2014 at 23:02
JasonCJasonC
191 silver badge7 bronze badges
1
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:machinenameadminuser cmd
See relevant help from Microsoft community.
answered Sep 30, 2013 at 16:05
MattMatt
1,7125 gold badges20 silver badges32 bronze badges
1
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:
- Open CMD
- Write
powershell -Command "Start-Process cmd -Verb RunAs"
and press Enter - A pop-up window will appear asking to open a CMD as administrator
Felix Dombek
13.3k17 gold badges78 silver badges127 bronze badges
answered Aug 26, 2015 at 1:05
GuiGui
2,2271 gold badge11 silver badges3 bronze badges
6
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"
answered Nov 10, 2018 at 9:29
StieglerStiegler
6896 silver badges8 bronze badges
1
Simple way I did after trying other answers here
Method 1: WITHOUT a 3rd party program (I used this)
- Create a file called
sudo.bat
(you can replacesudo
with any name you want) with following content
powershell.exe -Command "Start-Process cmd "/k cd /d %cd%" -Verb RunAs"
- Move
sudo.bat
to a folder in yourPATH
; if you don’t know what that means, just move these files toc:windows
- 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
- Download NirCmd and unzip it.
- Create a file called
sudo.bat
(you can replacesudo
with any name you want) with following content
nircmdc elevate cmd /k "cd /d %cd%"
- Move
nircmdc.exe
andsudo.bat
to a folder in yourPATH
; if you don’t know what that means, just move these files toc:windows
- Now
sudo
will work in Run dialog (win+r) or in explorer address bar (this is the best part :))
answered Oct 29, 2016 at 16:40
Dheeraj BhaskarDheeraj Bhaskar
18.4k9 gold badges63 silver badges66 bronze badges
12
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:
- Download it and unzip it.
nircmdc elevate cmd
windosu:
- Install it:
npm install -g windosu
(requires node.js installed) sudo cmd
answered Mar 21, 2014 at 15:28
Ricardo StuvenRicardo Stuven
4,6762 gold badges35 silver badges36 bronze badges
7
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)»
bluish
25.6k27 gold badges119 silver badges177 bronze badges
answered Feb 19, 2015 at 7:59
3
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 "
answered Apr 14, 2017 at 0:25
statlerstatler
1,2741 gold badge15 silver badges24 bronze badges
1
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).
- cmdadm.lnk (shortcut properties / Advanced… / Run as administrator = ON)
%SystemRoot%System32cmd.exe /k "cd /d"
- su.bat
@start cmdadm.lnk %cd%
Run with su
.
answered Dec 3, 2016 at 0:18
OgmiosOgmios
6487 silver badges12 bronze badges
3
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.
answered Sep 7, 2014 at 14:11
David RodriguezDavid Rodriguez
2,3921 gold badge17 silver badges15 bronze badges
4
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:WindowsSystem32runas.exe /user:Administrator /savecred cmd.exe
bluish
25.6k27 gold badges119 silver badges177 bronze badges
answered May 17, 2018 at 18:32
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-64elevate.exe
from the .zip
into C:Program Fileselevate
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.
answered Jun 11, 2017 at 16:33
seangwrightseangwright
16.7k6 gold badges41 silver badges54 bronze badges
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
answered May 14, 2019 at 9:19
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:WindowsSystem32 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
)
answered Mar 7, 2017 at 14:38
..
@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…
answered Feb 9, 2018 at 0:40
jOte-jOte-
514 bronze badges
2
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:DomainNameUserName "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.
answered Oct 7, 2021 at 14:18
1
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:
Here are the steps:
- Create this key:
HKEY_CLASSES_ROOTFoldershelldosherewithadmin
- Change its Default value to whatever you want to appear as the menu item text.
E.g. «DOS Shell as Admin« - Create another key:
HKEY_CLASSES_ROOTFoldershelldosherewithadmincommand
- and change its default value to this:
powershell.exe -Command "Start-Process -Verb RunAs 'cmd.exe' -Args '/k pushd "%1"'"
- 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.
not2qubit
13.3k8 gold badges89 silver badges122 bronze badges
answered Jul 18, 2020 at 21:11
rribasrribas
4151 gold badge6 silver badges6 bronze badges
For fans of Cygwin:
cygstart -a runas cmd
answered Nov 15, 2020 at 12:22
gavenkoagavenkoa
43.6k17 gold badges243 silver badges295 bronze badges
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:WindowsSystem32cmd.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.
answered Sep 21, 2021 at 10:15
Michel de RuiterMichel de Ruiter
6,7035 gold badges50 silver badges70 bronze badges
2
The quickest way by far is to:
CTRL+ALT+DELETE
- Run TASK MANAGER
- 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.
tomerpacific
4,38612 gold badges33 silver badges51 bronze badges
answered Aug 16, 2021 at 10:30
GarethGareth
591 gold badge1 silver badge6 bronze badges
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-
- Hit Windows+R and type
compmgmt.msc
which will open Computer Management window. - Go to System Tools -> Local Users and Groups -> Users
- You should see an account with name Administrator here(more info about this account can be found here).
- Right click on Administrator and select Properties.
- 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.
- 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
answered Dec 1, 2021 at 16:32
avmavm
3773 silver badges15 bronze badges
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%"
- Saved as
smartctl.cmd
- Create a shortcut for
smartctl.cmd
- Copy the shortcut to
C:Users#YourName#AppDataRoamingMicrosoftWindowsStartMenuPrograms
- Click search next to the start menu and input
smartctl
- Right click
Pin to Start
answered Dec 3, 2021 at 6:28
Just use the command:
runas /noprofile /user:administrator cmd
answered Jan 8, 2020 at 9:32
Use:
start
, run
, cmd
, then control+shift+enter
You’ll get UAC and then an elevated command shell.
answered Mar 28, 2021 at 2:36
Jeter-workJeter-work
7577 silver badges22 bronze badges
Install gsudo tool and use gsudo
command. UAC popup appears and eventually command prompt right in the current console window will be elevated:
C:UsersSomeone>net session
System error 5 has occurred.
Access is denied.
C:UsersSomeone>gsudo
C:UsersSomeone# net session
There are no entries in the list.
The tool can be installed using various package managers (Scoop, WinGet, Chocolatey).
answered Jul 16, 2022 at 20:51
Ilya SerbisIlya Serbis
20.5k6 gold badges81 silver badges72 bronze badges
1
Can use a temporary environment variable to use with an elevated shortcut (
start.cmd
setx valueName_betterSpecificForEachCase %~dp0
"%~dp0ascladm.lnk"
ascladm.lnk (shortcut)
_ propertiesadvanced"run as administrator"=yes
(to make path changes you’ll need to temporarily create the env.Variable
)
_ propertiestarget="%valueName_betterSpecificForEachCase%ascladm.cmd"
_ properties"start in"="%valueName_betterSpecificForEachCase%"
ascladm.cmd
setx valueName_betterSpecificForEachCase=
reg delete HKEY_CURRENT_USEREnvironment /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
Jee Mok
5,8498 gold badges46 silver badges75 bronze badges
answered Jul 25, 2018 at 23:28
iliailia
291 silver badge5 bronze badges
1
You can use the following syntax, I had the same question and did not think a script should be needed.
runas /profile /user:domainusername cmd
This worked for me, it may be different on your network.
answered Nov 29, 2019 at 15:28
I did it easily by using this following command in cmd
runas /netonly /user:AdministratorAdministrator 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)..
answered Aug 16, 2018 at 7:18
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.
Trooper Z
1,58013 silver badges31 bronze badges
answered Feb 25, 2019 at 14:11
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:Utilityregjump.exe HKCUSoftwareClasses.pdf"
answered Nov 14, 2014 at 23:55
MrCalvinMrCalvin
1,5531 gold badge16 silver badges23 bronze badges
7
I used runas /user:domainuser@domain cmd
which opened an elevated prompt successfully.
answered Mar 10, 2014 at 23:02
JasonCJasonC
191 silver badge7 bronze badges
1
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:machinenameadminuser cmd
See relevant help from Microsoft community.
answered Sep 30, 2013 at 16:05
MattMatt
1,7125 gold badges20 silver badges32 bronze badges
1
Командная строка от имени Администратора — режим запуска утилиты командной строки в операционной системе Windows с полными административными правами. Командная строка — инструмент для выполнения административных задач на компьютере, без использования графического интерфейса.
Приложение Командная строка работает в операционной системе Windows в двух режимах: обычного пользователя или администратора компьютера. Командная строка, запущенная от имени администратора Windows, предоставляет полный доступ к выполнению любых команд на компьютере, в отличие от режима обычного пользователя, где работают не все команды.
При работе на компьютере, часто возникает необходимость использовать командную строку (cmd.exe) в режиме повышенных прав администратора. Для применения тех или иных настроек системы, необходимо иметь полные административные права, например, на компьютере появились неполадки, пользователь нашел способ решить проблему, а для этого потребуется использовать командную строку.
Для решения проблемы, запустите командную строку с правами администратора, выполните необходимые действия в интерфейсе командной строки (интерпретаторе командной строки).
В инструкциях этой статьи мы рассмотрим разные способы, как открыть командную строку от имени администратора в операционной системе Windows: в Windows 10, в Windows 8.1, в Windows 8, в Windows 7. Здесь вы найдете 5 универсальных способов, работающие во всех версиях Виндовс, и некоторые способы, применимые только для некоторых версий ОС.
Запуск командной строки от имени администратора Windows — 1 способ
Данный способ подойдет для всех версий Windows: Windows 10, Windows 8.1, Windows 8, Windows 7. Для вызова командной строки с полными административными привилегиями, используется функция поиска в операционной системе.
В Windows 7 войдите в меню «Пуск», в Windows 8 и Windows 8.1 поведите курсор мыши к правому верхнему или нижнему краю Рабочего стола, в Windows 10 поле поиска находится на Панели задач.
- Введите в поисковое поле выражение «cmd» или «командная строка».
- Нажмите правой кнопкой мыши по приложению, показанному в результатах поиска, выберите «Запуск от имени администратора».
Как включить командную строку от имени администратора — 2 способ
Следующий способ, позволяющий открыть командную строку с полными правами, в разных версиях операционной системы Windows: запуск утилиты из меню «Пуск».
- Войдите в меню «Пуск» (в Windows1 и в Windows 8 нужно перейти на экран «Приложения»).
- Среди программ, в папке «Служебные — Windows» (в Windows 7 – «Стандартные») найдите программу «Командная строка».
- Щелкните по приложению правой кнопкой мыши, выберите «Запустить от имени администратора».
Как вызвать командную строку от имени администратора — 3 способ
Есть еще один способ для открытия командной строки от имени администратора в любой версии Windows. Для этого потребуется запустить утилиту cmd.exe непосредственно из папки, где она находится в операционной системе.
- Откройте в Проводнике системный диск «C:».
- Войдите в папку «Windows», перейдите в папку «System32».
- Кликните правой кнопкой мыши по приложению «cmd», в контекстном меню выберите «Запуск от имени администратора».
Как запустить командную строку с правами администратора — 4 способ
Другой универсальный способ, работающий во всех версиях Windows, начиная с Windows 8, выполняется с помощью Диспетчера задач.
- Запустите Диспетчер задач.
- Войдите в меню «Файл», выберите «Запустить новую задачу».
- В окне «Создание задачи», в поле открыть введите «cmd» (без кавычек), поставьте флажок напротив пункта «Создать задачу от имени администратора», а затем нажмите на кнопку «ОК».
Запуск командной строки с правами администратора — 5 способ
В этом способе мы создадим специальный ярлык для запуска приложения cmd.exe с правами администратора.
- Войдите в папку по пути: «C:WindowsSystem32».
- Нажмите на приложение «cmd» правой кнопкой мыши, в контекстном меню выберите «Отправить», далее «Рабочий стол (создать ярлык)».
- Щелкните по ярлыку правой кнопкой мыши, выберите «Свойства».
- В окне «Свойства», во вкладке «Ярлык» нажмите на кнопку «Дополнительно…».
- В окне «Дополнительные свойства» установите галку, напротив пункта «Запуск от имени администратора», нажмите на кнопку «ОК».
Командная строка Windows 10 от имени администратора
В начальных версиях Windows 10 можно было легко вызвать командную строку. Затем, Майкрософт несколько изменила свою политику: вместо командной строки предлагается использовать Windows PowerShell (более продвинутый аналог командной строки), поэтому некоторые способы запуска командной строки, перестали работать в операционной системе.
- Одновременно нажмите на клавиши «Win» + «X».
- В открывшемся окне вы увидите пункт «Командная строка (администратор)», находящийся на прежнем месте.
Командная строка от имени администратора Windows 8.1
Самый простой способ запуска командной строки в операционной системе Windows 10: из меню «Пуск» на Рабочем столе.
- На Рабочем столе кликните правой кнопкой мыши по меню «Пуск».
- В открывшемся меню нажмите на пункт «Командная строка (администратор)».
Командная строка от имени администратора Windows 8
Этот способ работает в операционных системах Windows 8 и Windows 8.1. В Проводнике Windows 10, вместо командной строки, нам предлагают использовать Windows PowerShell.
- Запустите Проводник Windows.
- Войдите на какой-нибудь диск или откройте любую папку.
- В окне Проводника щелкните левой кнопкой мыши по меню «Файл».
- В контекстном меню выберите сначала «Открыть командную строку», а затем «Открыть командную строку как администратор».
Командная строка от имени администратора Windows 7
В операционной системе Windows 7 работают все универсальные способы, описанные в этой статье:
- В меню «Пуск» введите «cmd» или «командная строка», кликните по приложению правой кнопкой, запустите от имени администратора.
- Войдите в меню «Пуск», далее «Все программы», затем «Стандартные», потом «Командная строка», с помощью правой кнопки запустите командную строку с правами администратора.
- Запуск «cmd.exe» из папки по пути: «C:WindowsSystem32».
- Открытие командной строки с помощью задания в Диспетчере задач.
- Со специально созданного ярлыка на Рабочем столе.
Выводы статьи
В случае необходимости, пользователь может запустить инструмент «командная строка» с полными правами от имени администратора в операционной системе Windows. В статье описаны разные способы запуска командной строки от имени администратора, работающие в операционных системах: Windows 10, Windows 8.1, Windows 8, Windows 7.
Источник