Automatically running a batch file as an administrator
How do I run a batch file from another batch file with administrator rights?
I have tried the RUNAS command, but it requires the administrator password.
I am searching for an alternative for running a batch file by right clicking on it and running as an administrator. I want to automate it from another batch file.
![]()
9 Answers 9
Put each line in cmd or all of theme in the batch file:
it works fine for me.
![]()
![]()
Create a shortcut to that batch file
Right click on that shortcut file and choose Properties
Click the Advanced button to find a checkbox for running as administrator
Check the screenshot below

![]()
You can use PowerShell to run b.bat as administrator from a.bat :
It will prompt the user with a confirmation dialog. The user chooses YES , and then b.bat will be run as administrator.
![]()
It will ask for the password the first time only. It will not ask for password again, unless the password is changed, etc.
If you’re trying to invoke a Windows UAC prompt (the one that puts the whole screen black and asks if you’re granting administrator privileges to the following task), RUNAS is not the smoothest way to do it, since:
- You’re not going to get prompted for UAC authorization, even if logged in as the administrator and
- RUNAS expects that you have the administrator password, even if your user is setup as a local administrator, in which case the former password is not a sound security practice, specially in work environments.
Instead, try to copy & paste the following code to ensure that your batch file runs with administrator privileges:
This solution works 100% under Windows 7, 8.1 and 10 setups with UAC enabled.
Как заставить bat запускаться от имени админа?
Была поставлена задача, нужно что-бы при запуске батника менялись сетевые настройки, я сделал вот так, оно работает только если запускать от имени админа.
но его нужно запускать из под обычного пользователя, для этого создал еще один батник
runas /user:Admin /savecred «D:\change ip.bat»
получается что при исполнении второго батника, запускается первый от имени админа, но изменения в сетевые настройки он не вносит с комментарием
так-же читал что эту проблему можно решить открытием учетки встроенного(скрытого) администратора, но это решение не годиться, так как выглядит совершенно не безопасно тем-более с доменными учетными записями.
- Вопрос задан более трёх лет назад
- 28534 просмотра
Простой 5 комментариев
- Вконтакте


С помощью runas привилегии повышаются действительно только для встроенного администратора.
Ничего страшного в том, что бы его активизировать я не вижу. Хотите подстраховаться — смените ему имя. Конечно нужно назначит нормальный пароль.
Но сохранять с помощью runas /savecred пароль администратора — это выстрел себе в ногу. С помощью этого сохраненного пароля и runas можно будет любую программу запускать с повышенными привилегиями из-под любого пользователя. Этим вы сделаете большую дыру в безопасности сети.
На самом деле не очень понятна цель этого мероприятия — вы меняете IP адрес. Зачем? Чувствую, что, то что вы хотите добиться, должно быть сделано по другому. Варианты:
1. Сделайте 2 IP на одном интерфейсе и пусть они всегда будут.
2. Организовать доступ в 172.16.11 подсеть через промежуточный шлюз, на котором в зависимости от некоторых условий можно разрешать доступ или нет.
3. Можно запускать netsh удаленно с админскими привилегиями, запускать, конечно должен админ, а не пользователь. Если у вас есть АД, то доменный админ может это делать, если АД нет, то на пользовательском компе нужно выставить ключ в реестре:
reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f
Этот ключ позволяет при сетевом доступе с админскими правами автоматически повышать привилегии. Локальных пользователей и их привилегии это не затрагивает.
Запуск скрипта с повышенными привилегиями [руководство]
Вариант 1) Правая кнопка мыши по Batch-файлу "Запуск от имени администратора".
Вариант 2) Сначала запустить командную строку (см. ниже), а в ней запустить на исполнение Batch-файл.
Запуск bat скрипта с пониженными привилегиями
Привет ☺ Как в bat скрипте, который запускается с правами администратора прописать запуск.
Изменение рабочего каталога при запуске батника с повышенными привилегиями
C:\Users\adm>echo Рабочий каталог — C:\Users\adm Рабочий каталог — C:\Users\adm никакого system32
Запуск скрипта с привилегиями администратора
Здравствуйте. Создал службу windows 10. Она должна запускать скрипт Powershell. Но что-то не.
Почему эта программа запускается с повышенными привилегиями?
Ресурса #24 нет, слой совместимости тоже не прописан, так откуда тогда знак щита? Как это у меня.
Как запустить командную строку от имени Администратора (с повышенными правами).
Способ 1:
Пуск
В окно поиска ввести CMD
Нажать Ctrl + Shift + Enter.
Способ 2:
Войти в диспетчер задач (Ctrl + Shift + Esc)
Вкладка "Процессы", кнопка "Отображать процессы всех пользователей".
Файл, Ctrl + Клик ЛКМ (левая кнопка мыши) по пункту "Новая задача (Выполнить . )".
Способ 3. Запуск Batch-файла с повышенными правами:
2. Создайте ярлык к этому файлу.
3. Зайдите в свойства ярлыка, выберите вкладку "Ярлык", кнопка "Дополнительно", отметьте галкой "Запускать от имени администратора".
Ярлык для запуска с запросом элевации прав готов.
- Открытие командной строки с правами администратора в нужной папке
- Добавление соответствующего пункта контекстного меню с помощью установщика CmdHereAsAdmin.inf (программа PowerToy).
- Рассматриваются Windows 7 и 8.
- Как открывать файлы из контекстного меню с полными правами
- Повышение прав из раздела реестра “runas”
- Повышение прав сторонними средствами
- Тонкости, которые нужно учитывать, при работе с UAC
- Практика: создание архива с полными правами из контекстного меню
- С какими правами работать?
- Назначение контроля учетных записей
- Администратор или пользователь?
- Повышение прав с запросом UAC и без него
- Современные программы и старые приложения
- Виртуализация файлов и реестра
- Использование сторонних утилит для повышения прав
- Запуск программ без запроса UAC
Сообщение было отмечено как решение
Решение
Элевация прав запуска BAT-файла (отображается диалог контроля учетных записей UAC)
Код: Dragokas
В ОС Windows Vista/7/8. запись в системные папки (такие как Windows, System32, корень диска C: ), запись в реестр (например, в улей HKLM) требует прав администратора.
Чтобы автоматически запускать батник с затребованием повышенных привилегий,
Вы можете воспользоваться одним из способов:
1) Через JScript-вставку без создания вспомогательного файла:
Из минусов обоих способов: батнику нельзя передавать аргументы запуска.
2) С использованием внешнего VBScript-сценария.
Приведенный пример создает временный VBS-скрипт, через который методом ShellExecute, verb — runas запускает повторно BAT-файл с повышенными правами.
3) С использованием mshta (способ от ComSpec):
Start Admin Console.cmd
Запускает новое окно консоли с повышенными правами и переходит в папку, где сам находится
Ожидает ввода команд от пользователя.
Как запустить VBScript, JScript с повышенными привилегиями?
1) Создайте к Вашему скрипту ярлык -> правой кнопкой мыши (ПКМ) по файлу скрипта -> "Создать ярлык".
2) В свойствах ярлыка (ПКМ по ярлыку)
на вкладке "Ярлык":
— в поле "Объект" допишите слева слово WSCRIPT и знак пробела
— нажмите "Применить"
— нажмите "Дополнительно"
Поставьте галочку "Запускать от имени администратора".
Нажмите "ОК" в обоих окнах.
Значок скрипта изменится на такой:
Теперь можете запускать скрипт через этот ярлык (с повышенными привилегиями).
Будет задан вопрос от "Контроля учетных записей", на который следует ответить утвердительно.
а можно допилить этот код так чтобы после согласия на разрешение прав окно батника пропадало а не висело пока выполняется команда? Заранее спасибо!
::
:: <— Здесь код Вашей основной программы
::
:: Эту строку не трогать. Ниже ничего не писать.
*/new ActiveXObject(‘Shell.Application’).ShellExecute (WScript.ScriptFullName,’Admin’,»,’runas’,1);
вот вставляю этот код в батник и он перестает висеть (открывается на секунду и закрывается и команда продолжает работать без окна)
но перестает запускаться от администратора(
можно ка кто эти два кода подружить?
Сообщение от valli_vasia
второй код я писал в предыдущем сообщении)
мне надо чтобы батник запускался от имени администратора и чтобы окно не висело во время выполнения команды (типо запустил батник он спросил права админа UACокно, я согласился и окно батника пропало а команда продолжалась бы) ну если бы подтверждение не выскакивало было бы еще лучше)
Is it possible to automatically run a batch file as administrator
I am wondering whether it is possible to automatically open a batch file as admin when you double-click on the batch file, because the commands need to be run with administrative rights.
Note: I already know about the solution of right-clicking on the file and clicking on Run As Administrator , but this is not an automatic solution.
![]()
9 Answers 9
Yes, you’re able to run a batch file with administrative rights. Unfortunately, you can’t do this directly from the batch file it self. You would need to first create a shortcut of that batch file and change the properties for that shortcut in order to make this work.
To create a shortcut, there are many ways but the simplest and the fastest way is by using the Send to option in the context menu.
Of course you can send the shortcut to where ever you would like. To elevate the batch file to run as admin, follow the steps below:
- Right-click the shortcut you just created (should be on the desktop or where ever you send it), and select ‘Properties’
- Under the Shortcut tab, click the Advanced. button.
- Check the Run as administrator checkbox and press OK to both the modal window and the main properties window.
- Run the shortcut by double-clicking it and the batch file should run as administrator.
![]()
1" == "" start %USERPROFILE%\Desktop\Shortcut.lnk && GOTO :EOF right below @echo off , and make the shortcut link to program.bat a instead of just program.bat .
As posted in an answer by Ben Gripka to another question:
Create a shortcut to that Batch file
Right-click the shortcut file
Click advance button to find a checkbox for running as administrator
Check the screenshot below

The accepted answer does indeed work. But I found that in Windows 7, I had to endure the UAC dialog each time the shortcut is clicked. This IMHO detracts significantly from the «automatically» in this question!
Then I found that in my own situation, the .bat file in question is to be run by Task Scheduler. In this case, checking the Run with highest privileges option on the General tab of the task, nicely takes care of the problem. The .bat is then run as administrator without any hassles.
PS: I didn’t realize I couldn’t upload images on this answer, ’cause I have a nice little screenshot sitting right with me now! Or can I?
You can use my script Batch_Admin to automatically elevate the Administrator for use in any type of Batch own script, or BAT or .CMD. This function ensures the work on a standard environment, with standard tools and in the same way in different Windows systems. It uses several standard and built-in Windows commands. Do not use any other external scripts. It can be used to call any program as Administrator, not just scripts Batch. It suffices to create a small script, which then call the program that requires permission Administartor. Place this in any search PATH folder (from %PATH%).
To use it, you simply insert the following line (exactly as) in its parent Batch script, which is to be run as Administrator. This is best done at the top of our parent script and it is best that first, which will be called via the CALL further, some sub-scripts (see detailed explanation below).
This can be inserted inside any child scripts, called by CALL syntax. To display a message while it is still does not have Administrator privileges, eg. for 5 seconds before calling Batch_Admin set the variable «ShowAdminInfo» on the number of seconds
So how it works:
• Calls UAC.ShellExecute through VBScript to pick up user permissions
• Batch runs the script, or BAT or CMD
• Script caller can have a long name spaces included in the call in quotes
• Give back all the parameters call the master script passed from the command line, as if there was no transmission of the call and start something from scratch, also with special characters, like exclamation marks (!) and percentage (%), and also with parentheses ()
• Holds a master script location if the call took place in the directory where this script is the master
• Auxiliary displays a message if we set before ourselves the variable «ShowAdminInfo», eg. for 5 seconds which can prevent the immediate passage of the rights of the Administrator giving additional information and the possibility of an informed decision. Examples of setting that must be set: SET ShowAdminInfo=5 By default, because this variable is not defined, it does not display.
• The script is calling also in the system search path % PATH% and from network resource, such as: \Computer\share\test.bat
• Prevents misunderstandings in writing the necessary auxiliary files when the script calls several Batch_Admin almost at the same time. It uses the random number from 1 to 100
• But, the best is to use it on parent script. The transition to Administrator rights always requires that you run the script completely again, in a new window, in a new environment, without recourse to the the variables are set previously in our script and values of these variables did not pass then to call as Administrator. Just the script will be executed again.
Below a complete script Batch_Admin. Extended information about this is on my site.