Restart windows bat file

How to shut down or restart the computer with a batch file

Below are steps on how to restart, shut down, and hibernate a Windows computer from a batch file or the command line.

Windows Vista, 7, 8, and 10

Microsoft Windows Vista, 7, 8, and 10 includes a command to shut down the computer through the command line, shortcut, or batch files. Below are the steps required for creating a shutdown, restart, and hibernate shortcut.

  1. Create a new shortcut.
  • How to create a Windows shortcut.
  1. For the location of the shortcut, enter one of the following commands, depending on what you want to do.

To shut down the computer, type the following line in the location text field.

To restart the computer, type the following line in the location text field.

To hibernate the computer, type the following line in the location text field.

  1. Click Next, and then for the name of the shortcut type either Shut down, Restart, or Hibernate and then click Finish.
  • For additional information about the shutdown command, see our shutdown command page.

After completing the above steps, double-click the shortcut icon to shut down, restart, or put the computer into hibernation.

After the shortcut is created, you can assign the shortcut a keyboard shortcut to shut down the computer using the keyboard. For more information, see: How do I create a Windows shortcut key?

If you want to create a batch file, you can add any of the above shutdown commands into the batch file with any other commands. For more information, see: How to make a batch file.

Shut down and restart shortcut in Windows XP

Microsoft Windows XP includes a new shutdown command that allows users to shut down the computer through the command line, shortcut, or batch files. Below are the steps required for creating a shutdown and restart shortcut.

  1. Create a new shortcut.
  • How to create a Windows shortcut.
  1. For the location of the shortcut, type one of the following commands, depending on what you want to do.

To shut down your computer, type the following line in the location.

To restart the computer, type the following line in the location.

  1. Click Next, and then for the name of the shortcut type either Shut down or Restart and then click Finish.

After completing the above steps, double-click the shortcut icon to shut down or restart the computer.

Shut down and restart shortcut in Windows 95, 98, and ME

Create a batch file with the following lines, corresponding to the action you want to perform.

Читайте также:  What is symlink in windows

Restarting the computer

Shut down the computer

When typing the above two lines, spacing is important. Also, make sure to enter the exit line at the bottom of the batch file in case Windows cannot restart the computer because of the open MS-DOS window.

Microsoft Windows 98 and Windows ME users can also run the following command to perform different forms of rebooting or shutting down.

Where n is equal to one of the numbers below, depending on the action you want the computer to perform.

  • 0 — LOGOFF
  • 1 — SHUTDOWN
  • 2 — REBOOT
  • 4 — FORCE
  • 8 — POWEROFF

Shut down and restart shortcut in MS-DOS

If you need to restart from MS-DOS, see the debug routines page for steps on how to write a debug routine to restart these computers.

Как выключить, перезапустить или выйти из Windows через файл bat?

Я использовал Remote Desktop Connection, чтобы попасть на рабочую станцию. Но в этой среде я не могу использовать параметры питания в меню «Пуск». Мне нужен альтернативный способ выключения или перезагрузки.

Как я могу контролировать состояние питания моего компьютера через командную строку?

Наиболее распространенные способы использования shutdown команды:

  • shutdown -s — Выключается.
  • shutdown -r — Перезагрузка.
  • shutdown -l — Выход из системы.

shutdown -h — зимует.

Примечание. Существует распространенная ошибка, когда пользователи считают -h «помощь» (что она делает для любой другой программы командной строки . за исключением случаев shutdown.exe , когда это означает «спящий режим»). Затем они запускаются shutdown -h и случайно выключают свои компьютеры. Остерегайтесь этого.

shutdown -i — «Интерактивный режим». Вместо выполнения действия он отображает диалоговое окно с графическим интерфейсом.

  • shutdown -a — Отмена предыдущей команды выключения.
  • Команды выше могут быть объединены с этими дополнительными опциями:

    • -f — Принудительно завершает программы. Предотвращает зависание процесса выключения.
    • -t — Устанавливает время до выключения. Используйте -t 0 для немедленного выключения.
    • -c — Добавляет сообщение о выключении. Сообщение попадет в журнал событий.

    -y — Принудительно отвечает «да» на все запросы на отключение.

    Примечание. Этот параметр не задокументирован ни в одной официальной документации. Это было обнаружено этими пользователями StackOverflow .

    Я хочу убедиться, что некоторые другие действительно хорошие ответы также упоминаются вместе с этим. Здесь они в произвольном порядке.

    Перезапуск BAT файла

    Перезапуск bat-файла через определённый промежуток времени
    Здравствуйте . есть bat файл , он иногда подвисает и требуется его полная перезагрузка. Может быть.

    Один bat-файл запускает по очереди два других bat-файла
    Имеются две папки в одной драйвера в второй программы решил сделать установку этого хозяйства с.

    Запуск файла в директории с .bat, когда .bat запущен от имени администратора
    Здравствуйте. Имею бат, он должен запускать файл » \n1.bat». Но если даже.

    Создать bat-файл при помощи другого bat-файла
    Добрый вечер всем форумчанам! Прошу помощи. Решил заморочиться и создать bat файл при помощи.

    Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.

    Последовательный запуск нескольких параллельных bat файлов из bat файла
    Добрый день! Есть 6 bat файлов. Необходимо запустить 2 последовательных вызова запуска 3.

    Последовательный запуск нескольких BAT-файлов из основного BAT-файла
    Доброго времени суток всем. Помогите кто понимает.. Есть bat. @echo off start «» «D:\$\Pale.

    Можно ли получить имя bat-файла в этом же bat-файле?
    Запускаю прогу со входными аргументами из батника. Последний аргумент — имя выходного файла. Хочу.

    Запись команд из одного bat-файла в другой bat-файл
    Предположил что: в 1 bat: echo echo my_text >> my_file >> new.bat и хотел что бы получилось так.

    Помогите с запуском bat-файла через bat-файл
    Расклад таков: 1. У меня есть bat файл(help.bat). 2. Нужно написать ещё один чтобы он запускал.

    Неправильно работает EXE-файл, скомпилированный из BAT-файла с помощью программы Bat To Exe Converter
    Сдрасте люди, я пришел к вам с того самого мира, или как то так У меня уже мозги кипят на.

    Stop and Start a service via batch or cmd file?

    How can I script a bat or cmd to stop and start a service reliably with error checking (or let me know that it wasn’t successful for whatever reason)?

    16 Answers 16

    Use the SC (service control) command, it gives you a lot more options than just start & stop .

    tell you whether they have succeeded or failed pretty clearly. For example

    If running from a batch file, you have access to the ERRORLEVEL of the return code. 0 indicates success. Anything higher indicates failure.

    As a bat file, error.bat :

    The output looks like this:

    Return Codes

    Edit 20.04.2015

    The NET command does not return the documented Win32_Service class return codes (Service Not Active,Service Request Timeout, etc) and for many errors will simply return Errorlevel 2.

    You can use the NET START command and then check the ERRORLEVEL environment variable, e.g.

    Disclaimer: I’ve written this from the top of my head, but I think it’ll work.

    Instead of checking codes, this works too

    I have created my personal batch file for this, mine is a little different but feel free to modify as you see fit. I created this a little while ago because I was bored and wanted to make a simple way for people to be able to input ending, starting, stopping, or setting to auto. This BAT file simply requests that you input the service name and it will do the rest for you. I didn’t realize that he was looking for something that stated any error, I must have misread that part. Though typically this can be done by inputting >> output.txt on the end of the line.

    The %var% is just a way for the user to be able to input their own service into this, instead of having to go modify the bat file every time that you want to start/stop a different service.

    If I am wrong, anyone can feel free to correct me on this.

    Using the return codes from net start and net stop seems like the best method to me. Try a look at this: Net Start return codes.

    Syntax always gets me. so.

    Here is explicitly how to add a line to a batch file that will kill a remote service (on another machine) if you are an admin on both machines, run the .bat as an administrator, and the machines are on the same domain. The machine name follows the UNC format \myserver

    In this case. p4_1 was both the Service Name and the Display Name, when you view the Properties for the service in Service Manager. You must use the Service Name.

    For your Service Ops junkies. be sure to append your reason code and comment! i.e. ‘4’ which equals ‘Planned’ and comment ‘Stopping server for maintenance’

    We’d like to think that «net stop » will stop the service. Sadly, reality isn’t that black and white. If the service takes a long time to stop, the command will return before the service has stopped. You won’t know, though, unless you check errorlevel.

    The solution seems to be to loop round looking for the state of the service until it is stopped, with a pause each time round the loop.

    I’m seeing the first service take a long time to stop, then the «net stop» for a subsequent service just appears to do nothing. Look at the service in the services manager, and its state is still «Started» — no change to «Stopping». Yet I can stop this second service manually using the SCM, and it stops in 3 or 4 seconds.

    How do I shutdown, restart, or log off Windows via a bat file?

    I’ve been using Remote Desktop Connection to get into a workstation. But in this environment, I cannot use the power options in Start Menu. I need an alternative way to shutdown or restart.

    How do I control my computer’s power state through the command line?

    10 Answers 10

    The most common ways to use the shutdown command are:

    • shutdown -s — Shuts down.
    • shutdown -r — Restarts.
    • shutdown -l — Logs off.

    shutdown -h — Hibernates.

    Note: There is a common pitfall wherein users think -h means «help» (which it does for every other command-line program. except shutdown.exe , where it means «hibernate»). They then run shutdown -h and accidentally turn off their computers. Watch out for that.

    shutdown -i — «Interactive mode». Instead of performing an action, it displays a GUI dialog.

  • shutdown -a — Aborts a previous shutdown command.
  • The commands above can be combined with these additional options:

    • -f — Forces programs to exit. Prevents the shutdown process from getting stuck.
    • -t — Sets the time until shutdown. Use -t 0 to shutdown immediately.
    • -c — Adds a shutdown message. The message will end up in the Event Log.

    -y — Forces a «yes» answer to all shutdown queries.

    Note: This option is not documented in any official documentation. It was discovered by these StackOverflow users.

    I want to make sure some other really good answers are also mentioned along with this one. Here they are in no particular order.

    Читайте также:  Kyocera ecosys p2335dn драйвер linux
    Оцените статью