- Команда Shutdown: выключение и перезагрузка Windows из командной строки
- Выключение Windows командой Shutdown
- Перезагрузка Windows
- Завершение сеанса пользователя
- Перевод компьютера в режим гибернации
- Перезагрузка компьютера с сообщением пользователям
- Отложенное выключение / перезагрузка компьютера
- Отмена выключения / перезагрузки компьютера
- Перезагрузить компьютер немедленно
- Запуск команды shutdown на удаленных компьютерах
- Графический интерфейс команды shutdown
- Ярлык для перезагрузки компьютера
- How to shut down or restart the computer with a batch file
- Windows Vista, 7, 8, and 10
- Shut down and restart shortcut in Windows XP
- Shut down and restart shortcut in Windows 95, 98, and ME
- Restarting the computer
- Shut down the computer
- Shut down and restart shortcut in MS-DOS
- FIX: Windows 10 Restarts Instead of Shutting Down
- Repair Corrupt System Files
- Solution 1: Disable fast startup in Power Options
- Solution 2: Uninstall the ON/OFF by Gigabyte application
- Solution 3: Reconfiguring Network Adapter
- Solution 4: Changing Registry Configurations
Команда Shutdown: выключение и перезагрузка Windows из командной строки
Утилита командной строки shutdown является встроенной командой Windows, которая позволяет перезагрузить, выключить компьютер, перевести его в спящий режим или завершить сеанс пользователя. В этой инструкции мы покажем основные примеры использования команды shutdown в Windows (все рассмотренные команды запускаются в окне Выполнить — Win+R ->, в командной строке cmd.exe или в консоли PowerShell).
Команда shutdown имеет следующий синтаксис:
shutdown [/i | /l | /s | /sg | /r | /g | /a | /p | /h | /e | /o] [/hybrid] [/soft] [/fw] [/f] [/m \\компьютер][/t xxx][/d [p|u]xx:yy [/c «комментарий»]]
Как вы видите, у команды довольно много опций, а также есть возможность выполнять операции выключения/перезагрузки на удаленном компьютере.
Выключение Windows командой Shutdown
Для выключения ОС Windows и компьютера необходимо использовать команду shutdown с ключом /s.
Перезагрузка Windows
Чтобы перезагрузить компьютер, необходимо добавить параметр /r. После выполнения этой команды Windows корректно перезагрузится.
Завершение сеанса пользователя
Чтобы завершить текущую сессию пользователя (logout), нужно выполнить команду:
Эта команда аналогично выполнению команды logoff.
Перевод компьютера в режим гибернации
Для перевода компьютер в режим гибернации (в этом режиме все содержимое памяти записывается в файл hyberfil.sys на диск и компьютер переходит в спящий режим с пониженным электропотреблением), выполните команду:
Перезагрузка компьютера с сообщением пользователям
Вы можете предупредить всех пользователей Windows о предстоящем выключении / перезагрузки компьютера или сервера, отправив сообщение во все активные сессии (как правило эта возможность используется на терминальных RDS серверах, за которыми одновременно работают несколько пользователей, каждый в своей собственной RDP сессии).
shutdown /r /c “Этот сервер будет перезагружен через 60 секунд.”
Отложенное выключение / перезагрузка компьютера
Можно выключить или перезагрузить компьютер с определенной задержкой (по таймеру). С помощью опции /t можно указать интервал времени (в секундах), через который ПК/сервер будет перезагружен или выключен. Тем самым вы можете предоставить пользователям дополнительное время для того, чтобы успеть сохранить открытые файлы и корректно закрыть приложения. Эту опцию удобно использовать совместно с отправкой сообщения. В этом примере мы указываем, что Windows будет выключена через 10 минут (600 секунд) и информируем пользователей сообщением.
shutdown /s /t 600 /c «Сервер будет выключен через 10 минут. Сохраните свои документы!»
Пользователю будет выдано предупреждение о запланированном выключении: Ваш сеанс будет завершен.
Если задержка очень длительная, например, 100 минут (6000 секунд), то вместо предупреждающего окна появляется всплывающее сообщение в нижнем правом углу экрана: «Ваш сеанс будет завершен. Работа Windows будет завершена через 100 мин».
Отмена выключения / перезагрузки компьютера
После запуска команды выключения или перезагрузки Windows, по умолчанию утилита shutdown ожидает 60 секунд, не выполняя никаких действия. Администратора может отменить перезагрузку или выключение устройства, если в течении этого времени успеет выполнить команду:
После отмены выключения появится всплывающее сообщение в нижнем правом углу экрана: «Выход из системы отменен. Запланировано завершение работы отменено».
Перезагрузить компьютер немедленно
Чтобы выключить или перезагрузить компьютер немедленно, не ожидая стандартные 60 секунд, нужно указать значение 0 для параметра /t. Например, для немедленной перезагрузки компьютера:
Очень важный ключ /f. Я использую его практически всегда при выключении или перезагрузки серверов Windows. Данный атрибут обеспечивает принудительное завершение всех запущенных программ и процессов, не ожидая подтверждения от пользователя (не будем же мы ждать подтверждения закрытия программ от всех пользователей на терминальном сервере, его можно просто не дождаться).
Следующая команда выполнит перезагрузку компьютера с автоматическим запуском всех зарегистрированных приложений после перезагрузки (имеются в виду приложения, зарегистрированные в системе с использованием функции API RegisterApplicationRestart).
Запуск команды shutdown на удаленных компьютерах
Вы можете перезагрузить удаленный компьютер по сети, для этого у вас должен быть к нему сетевой доступ, а учетная запись, из-под которой запускается команда shutdown должна входить в группу локальных администраторов на удаленном компьютере (сервере):
shutdown /r /t 120 /m \\192.168.1.100
Если все указанные условия выполняются, но при выполнении команды shutdown появляется ошибка ”Отказано в доступе (5)”, на удаленном компьютере нужно разрешить удаленный доступ к административным ресурсам (C$, ADMIN$), изменив значение параметра LocalAccountTokenFilterPolicy на 1.
reg add «HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System» /v «LocalAccountTokenFilterPolicy» /t REG_DWORD /d 1 /f
Если вам необходимо удаленно перезагрузить множество компьютеров, их список можно сохранить в текстовый файл и запустить удаленную перезагрузку всех компьютеров с помощью такого PowerShell скрипта:
$sh_msg = «Ваш компьютер будет автоматически перезагружен через 10 минут. Сохраните свои файлы и закройте запущенные программы»
$sh_delay = 600 # секунд
$computers = gc C:\PS\PC-list.txt
foreach ($comp in $computers)
<
& ‘C:\Windows\System32\SHUTDOWN.exe’ «-m \\$comp -r -c $sh_msg -t $sh_delay»
>
Графический интерфейс команды shutdown
Для тех, кому не комфортно работать в командной строке, есть графический интерфейс для команды shutdown, чтобы его вызвать, наберите:
Как вы видите, в диалоге удаленного завершения работы вы можете добавить несколько компьютеров, которые нужно перезагрузить/выключить, указать текст уведомления и задать причину выключения для сохранения в журнале Windows.
Ярлык для перезагрузки компьютера
Для удобства пользователей вы можете создать на рабочем столе ярлыки для выключения или перезагрузки компьютера с нужными настройками. Такой ярлык может быть полезен для выполнения перезагрузки из RDP сессии, когда отсутствуют кнопки перезагрузки/завершения работы компьютера в меню Пуск.
Если вы хотите, чтобы ваш компьютер или сервер всегда выключался / перезагружался в определенное время, вы можете добавить команду shutdown с определенными параметрами в планировщик заданий Windows taskschd.msc.
Например, следующее задание планировщика будет ежедневно перезагружать компьютер ночью в 0:00.
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.
- Create a new shortcut.
- How to create a Windows shortcut.
- 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.
- 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.
- Create a new shortcut.
- How to create a Windows shortcut.
- 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.
- 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.
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.
FIX: Windows 10 Restarts Instead of Shutting Down
Countless Windows 10 have complained of their computers experiencing shutdown problems immediately after they have been upgraded to Windows 10. The most common of the shutdown problems that Windows 10 may bring to any computer that is updated to it is the computer restarting instead of shutting down whenever the user shuts it down.
In such cases, your computer will restart 5-10 seconds after it powers down regardless of whether you turn it off by clicking on the Shut down button or by ordering the computer to shut down using a Command Prompt. In addition, putting your computer to sleep by clicking on the Sleep button also results in it waking up after 5-10 seconds. Even if your computer goes into Sleep mode if it is left idle, its screen will turn back on in a couple of minutes. The only way for Windows 10 users suffering from this problem to actually turn their computers off is to unplug them from their power supplies, remove their batteries (for laptops) or hold down their power buttons for 3-10 seconds (for desktop computers).
The cause of this issue has now been revealed as the fast startup feature that Microsoft has introduced with Windows 10 – a feature that is actually meant to allow Windows 10 computers to boot up faster when they are coming out of a shutdown. The following are the two solutions that have proven to be highly effective against this issue:
Repair Corrupt System Files
Download and run Restoro to scan for corrupt files from here, if files are found to be corrupt and missing repair them and then check if it fixes the issue, if not then proceed with Solutions listed below.
Solution 1: Disable fast startup in Power Options
For almost 85% of the people who have been affected by this restart instead of shutdown issue, disabling fast startup in Power Options took care of the problem. To disable fast startup in Power Options, you need to:
Open Control Panel.
Switch to Icons View.
Click on Power Options.
Click on Choose what the power buttons do in the left pane.
In the System Settings dialog, click on the blue colored Change settings that are currently unavailable option.
Confirm the action if prompted to do so by UAC.
In the Shutdown settings section, uncheck the checkbox beside the Turn on fast startup (recommended) Click on save changes. This will disable fast startup on your computer, and the next time you shut your computer down, it will actually shut down for good and not restart on its own.
Solution 2: Uninstall the ON/OFF by Gigabyte application
If Solution 1 didn’t work for you, a scenario which is quite unlikely, the fact of the matter may be that fast startup is not the culprit behind your computer restarting itself instead of shutting down. In the case of a select few computers that were affected by this issue – computers that were manufactured by Gigabyte Technology Co., Ltd. – the root of this issue was a Gigabyte application named ON/OFF. If your computer does have the On/OFF by Gigabyte application, it may very well be the cause of this problem in your cause, and all you need to do to get rid of this issue is uninstall this application.
Navigate to Apps/Programs.
Scroll down, locate and click on ON/OFF by Gigabyte.
Click on Uninstall and wait for the program to be removed.
As soon as the program has been uninstalled, your computer will start shutting down as it should.
Solution 3: Reconfiguring Network Adapter
In some cases, the Network Adapter has the permissions to wake the computer. This can be an issue if the Network that you are connected to constantly signals the computer to remain awake. Therefore, in this step, we will be disabling this setting. In order to do that:
- Press “Windows” + “R” keys simultaneously to open the Run prompt.
- Type in “devmgmt.msc” and press “Enter“.
Typing “devmgmt.msc” in the run prompt.
- Double–click on the “NetworkAdapter” dropdown and then doubleclick on the adapter being used by the computer.
- Click on the “PowerManagement” tab and uncheck the “Allowthisdeviceto wakethecomputer” option.
Clicking on the power management tab and unchecking the “Allow this device to wake up the computer” option
- Click on “OK” to save your settings and check to see if the issue persists.
Solution 4: Changing Registry Configurations
It is possible that Power down after shutdown has been disabled in the Registry. Therefore, in this step, we will be changing the Registry settings to immediately power down the computer after pressing shutdown. In order to do that:
- Press “Windows” + “R” keys simultaneously to open the Run prompt.
- Type in “regedit” and press “Enter“.
Typing in “Regedit” and pressing “Enter”
- Navigate to the following address
- DoubleClick on the “PowerDownAfterShutdown” entry in the right pane and type “1” in the “Value” option.
Double-clicking on the “Powerdownaftershutdown” entry and changing the value
- Press “OK” to save your changes and check to see if the issue persists.