В Windows доступно несколько команд, которые позволяют выключить или перезагрузить локальный или удаленный компьютер. В этой статье мы рассмотрим, как использовать команду shutdown и PowerShell командлеты Restart-Computer и Stop-Computer для выключения/перезагрузки Windows.
Содержание:
- Использование команды shutdown в Windows
- Перезагрузка удаленных компьютеров командой shutdown
- Перезагрузка и выключение Windows с помощью PowerShell
Использование команды 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.
shutdown /s
Перезагрузка Windows
Чтобы перезагрузить компьютер, необходимо добавить параметр /r. После выполнения этой команды Windows корректно перезагрузится.
shutdown /r
Завершение сеанса пользователя
Чтобы завершить текущую сессию пользователя (logout), нужно выполнить команду:
shutdown /l
Эта команда аналогично выполнению команды logoff.
Перевод компьютера в режим гибернации
Для перевода компьютер в режим гибернации (в этом режиме все содержимое памяти записывается в файл hyberfil.sys на диск и компьютер переходит в спящий режим с пониженным электропотреблением), выполните команду:
shutdown /h
Перезагрузка компьютера с сообщением пользователям
Вы можете предупредить всех пользователей Windows о предстоящем выключении / перезагрузки компьютера или сервера, отправив сообщение во все активные сессии (как правило эта возможность используется на терминальных RDS серверах, за которыми одновременно работают несколько пользователей, каждый в своей собственной RDP сессии).
shutdown /r /c “Этот сервер будет перезагружен через 60 секунд.”
Отложенное выключение / перезагрузка компьютера
Можно выключить или перезагрузить компьютер с определенной задержкой (по таймеру). С помощью опции /t можно указать интервал времени (в секундах), через который ПК/сервер будет перезагружен или выключен. Тем самым вы можете предоставить пользователям дополнительное время для того, чтобы успеть сохранить открытые файлы и корректно закрыть приложения. Эту опцию удобно использовать совместно с отправкой сообщения. В этом примере мы указываем, что Windows будет выключена через 10 минут (600 секунд) и информируем пользователей сообщением.
shutdown /s /t 600 /c "Сервер будет выключен через 10 минут. Сохраните свои документы!"
Пользователю будет выдано предупреждение о запланированном выключении: Ваш сеанс будет завершен.
Если задержка очень длительная, например, 100 минут (6000 секунд), то вместо предупреждающего окна появляется всплывающее сообщение в нижнем правом углу экрана: «Ваш сеанс будет завершен. Работа Windows будет завершена через 100 мин».
Отмена выключения / перезагрузки компьютера
После запуска команды выключения или перезагрузки Windows, по умолчанию утилита shutdown ожидает 60 секунд, не выполняя никаких действия. Администратор может отменить перезагрузку или выключение устройства, если в течении этого времени успеет выполнить команду:
shutdown /a
После отмены выключения появится всплывающее сообщение в нижнем правом углу экрана: «Выход из системы отменен. Запланировано завершение работы отменено».
Перезагрузить Windows немедленно
Чтобы выключить или перезагрузить компьютер немедленно, не ожидая стандартные 60 секунд, нужно указать значение 0 для параметра /t. Например, для немедленной перезагрузки компьютера:
shutdown /r /t 0
Очень важный ключ /f. Я использую его практически всегда при выключении или перезагрузки серверов Windows. Данный атрибут обеспечивает принудительное завершение всех запущенных программ и процессов, не ожидая подтверждения от пользователя (не будем же мы ждать подтверждения закрытия программ от всех пользователей на терминальном сервере, его можно просто не дождаться).
Следующая команда выполнит перезагрузку компьютера с автоматическим запуском всех зарегистрированных приложений после перезагрузки (имеются в виду приложения, зарегистрированные в системе с использованием функции API RegisterApplicationRestart).
shutdown /g
Ярлык для перезагрузки компьютера
Для удобства пользователей вы можете создать на рабочем столе ярлыки для выключения или перезагрузки компьютера с нужными настройками. Такой ярлык может быть полезен для выполнения перезагрузки из RDP сессии, когда отсутствуют кнопки перезагрузки/завершения работы компьютера в меню Пуск.
Перезагрузка Windows в определенное время
Чтобы всегда перезагружать/выключать компьютер или сервер в определенное время, вы можете добавить команду shutdown в планировщик заданий Windows taskschd.msc.
Например, следующее задание планировщика будет ежедневно перезагружать компьютер ночью в 0:00.
Либо вы можете создать новое задание планировщика из PowerShell:
$Trigger= New-ScheduledTaskTrigger -At 00:00am -Daily
$User= "NT AUTHORITY\SYSTEM"
$Action= New-ScheduledTaskAction -Execute "shutdown.exe" -Argument "–f –r –t 120"
Register-ScheduledTask -TaskName "RebootEvertyNight_PS" -Trigger $Trigger -User $User -Action $Action -RunLevel Highest –Force
Перезагрузка удаленных компьютеров командой 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
Если для подключения к удаленному компьютеру нужно указать учетные данные пользователя, можно использовать команду:
net use \\192.168.31.10 /u:corp\username
shutdown /s /t 60 /f /m \\192.168.31.10
Если вам необходимо удаленно перезагрузить множество компьютеров, их список можно сохранить в текстовый файл и запустить удаленную перезагрузку всех компьютеров с помощью такого 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, чтобы его вызвать, наберите:
shutdown /i
Как вы видите, в диалоге удаленного завершения работы вы можете добавить несколько компьютеров, которые нужно перезагрузить/выключить, указать текст уведомления и задать причину выключения для сохранения в журнале Windows.
Перезагрузка и выключение Windows с помощью PowerShell
В PowerShell есть две команды для выключения и перезагрузки компьютера: Restart-Computer и Stop-Computer. Обе команды позволяют выключить или перезагрузить локальный или удаленный компьютер по сети.
Для перезагрузки Windows выполните:
Restart-Computer -force
Чтобы выключить компьютер:
Stop-Computer
По умолчанию перезагрузка начнется через 5 секунд. Можно увеличить задержку перед перезагрузкой:
Restart-Computer –delay 15
У обоих командлетов есть параметр
–ComputerName
, который позволяет задать список удаленных компьютеров.
Например, чтобы удаленно выключить два сервера Windows:
Stop-Computer -ComputerName "Server01", "Server02"
Можно указать учетные данные администратора для подключения к удаленному хосту:
$Creds = Get-Credential
Restart-Computer -ComputerName $Names -Credential $Creds
Для подключения к удаленным компьютерам используется WMI и DCOM (он должны быть включен и настроен). Если WMI не настроен, при запуске команды появится ошибка:
Restart-Computer : Failed to restart the computer wks-t1122h2 with the following error message: Access is denied. Exception from HRESULT: 0x80070005 (E_ACCESSDENIED).
Если на удаленном компьютере настроен WinRM (Windows Remote Management), вы можете использовать для подключения WSman вместо WMI:
Restart-Computer -ComputerName wks-t1122h2 -Protocol WSMan
Если на удаленном компьютер есть активные сессии пользователей, при запуске Restart-Computer появится ошибка:
Restart-Computer : Failed to restart the computer wks-t1122h2 with the following error message: The system shutdown cannot be initiated because there are other users logged on to the computer.
Для принудительной перезагрузки нужно добавить параметр -Force:
Restart-Computer -ComputerName wks-t1122h2 –Force
С помощью параметра -For можно перезагрузить компьютер и дождаться, когда он будет доступен. Например, вы хотите убедиться, что удаленный компьютер успешно перезагрузится и на нем стартовала служба WinRM, позволяющая подключиться к нему через WS-Management:
Restart-Computer -ComputerName wks-t1122h2 -Wait -For WinRM
Restarting computer wks-t1122h2 Verifying that the computer has been restarted.
Можно дождаться запуска службы удаленного рабочего стола (RDP) или любой другой службы Windows:
Restart-Computer -ComputerName wks-t1122h2 -Wait -For TermService
Если нужно одновременно перезагрузить несколько хостов, можно использовать возможности параллельного запуска команд в версии PowerShell 7.x.
Например, вы можете получим список Windows Server в определенном контейнере (Organizational Unit) Active Directory с помощью командлета Get-ADComputer и перезагрузить их одновременно:
$Computers = (Get-ADComputer -Filter 'operatingsystem -like "*Windows server*" -and enabled -eq "true"' -SearchBase "OU=Servers,DC=winitpro,DC=loc").Name
$Computers | ForEach-Object -Parallel { Restart-Computer -ComputerName $_ -Force} -ThrottleLimit 3
(Image credit: Future)
Although, on Windows 10, you can conveniently sign out, shut down, restart, or hibernate your computer from the Start menu or Lock screen, the system also includes the shutdown.exe tool that allows you to perform the same power operations through Command Prompt.
It is also a more powerful tool since, in addition to the common tasks, the command-line tool supports more advanced options, including the ability to record the reason for the event, display custom messages to the end-user, and even use the tool to shut down and restart remote devices.
You can use this tool at any time. However, it will usually come in handy if you spend most of your time in the Command Prompt terminal, you need to create a script that involves restarting the computer, or you are making system changes, and you want to record a reason for the restart or shutdown event.
This guide will walk you through how to use the shutdown.exe command-line tool to shut down and restart local and remote computers.
How to turn off computer with shutdown command
To shut down the computer manually with Command Prompt, use these steps:
- Open Start.
- Search for Command Prompt, right-click the top result, and select the Run as administrator option.
- Type the following command to gracefully shut down the device after one minute and press Enter: shutdown /s
- Type the following command to shut down the device after a specific time and press Enter: shutdown /s /t TIME
In the command, replace TIME for the second to wait before the device begins the shutdown process. For example, this command turns off the computer after five seconds: shutdown /s /t 5
- Quick tip: You can also use «0» for the time to turn off the device immediately. If the time is greater than zero, then the /f option will be applied automatically.
- Type the following command to shut down the computer without waiting or warning and press Enter: shutdown /p
- Type the following command to shut down, forcing all apps to close without warning, and press Enter: shutdown /s /f
Once you complete the steps, the computer will execute the shutdown process depending on your specified options.
Shut down specifying reason
To turn off the device recording for a specific reason on Windows 10, use these steps:
- Open Start.
- Search for Command Prompt, right-click the top result, and select the Run as administrator option.
- Type the following command to include a reason for the shutdown and press Enter: shutdown /s /d p:MAJOR-NUMBER:MINOR-NUMBER
In the command, change the MAJOR-NUMBER:MINOR-NUMBER for the numbers that represent the reason. You can determine all the available major and minor reason numbers by running the shutdown /? command. For example, this command shuts down the device, recording the «Operating System: Service pack (Planned)» reason: shutdown /s /t 1 /d p:2:16. You can also switch the /s for the /r option if you want to specify a reason for the restart in the command. Here’s how: shutdown /r /t 1 /d p:2:16
- Type the following command to power off the computer specifying a reason as unplanned and press Enter: shutdown /s /t 1 /d u:2:16
The above command will shut down the device, recording the «Operating System: Service pack (Unplanned)» reason.
After you complete the steps, the Windows 10 device will shut down and log the specified reason.
You can always view the shutdown logs in Event Viewer > Windows Logs > System and look for the «Information» event with the User32 source and with the «Event ID» of 1074.
Shut down with custom dialog message
To shut down a computer showing a dialog message alerting the user of the action, use these steps:
- Open Start.
- Search for Command Prompt, right-click the top result, and select the Run as administrator option.
- Type the following command to shutdown the device showing a custom dialog message and press Enter: shutdown /s /t TIME /c «MESSAGE»
In the command, replace TIME with the number of seconds before shutting down the computer, and replace MESSAGE with the custom text you want to display to the user. For example, this command displays the «Updating XYZ company app» before shutting down the computer after one minute: shutdown /s /t 60 /c «Updating XYZ company app.» You can also switch the /s for the /r option if you want to show a message for the restart in the command. Here’s how: shutdown /r /t 60 /c «Updating XYZ company app.»
Once you complete the steps, Windows 10 will display the «Updating XYZ company app» message to the user and power off the computer after 60 seconds.
How to turn off remote computer with shutdown command
The shutdown command-line tool also allows you to remotely turn off or restart a device. However, the tool is limited, and you will perform extra steps to get it working.
Configure remote device
To set up the remote computer to allow remote command executions, use these steps:
Warning: This is a friendly reminder that editing the Registry is risky and can cause irreversible damage to your installation if you don’t do it correctly. It’s recommended to make a full backup of your computer before proceeding.
- Open Start.
- Search for Command Prompt, right-click the top result, and select the Run as administrator option.
- Type the following command to disable the User Account Control for remote executions and press Enter: reg add HKLM\Software\Microsoft\windows\CurrentVersion\Policies\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f
After you complete the steps, the device will be open to receive commands remotely from authenticated users.
If you want to revert the changes to improve the device security, you can use the same instructions outlined above, but in step 3, make sure to run this command: reg add HKLM\Software\Microsoft\windows\CurrentVersion\Policies\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 0 /f.
Shut down remote device
To use the Command Prompt to shut down a computer remotely, use these steps:
- Open Start.
- Search for Command Prompt, right-click the top result, and select the Run as administrator option.
- Type the following command to connect to the IPC$ share (or null session connection) and press Enter: net use \\REMOTE-PC\ipc$
In the command, replace REMOTE-PC with the name or IP address of the remote computer. For example, this command connects to the computer: net use \\10.1.4.120\ipc$
- Confirm the account name located in the remote device and press Enter.
- Confirm the account password and press Enter.
- Type the following command to restart the remote computer and press Enter: shutdown /r /m \\REMOTE-PC /t TIME /c «COMMENT» /f
In the command, replace REMOTE-PC for the name or IP address of the remote computer, TIME for the number of seconds to wait before beginning the shutdown process, and replace COMMENT for the custom dialog you want to send the user. For example, this command will notify the user and force the device to close all applications without warnings after one minute: shutdown /r /m \\10.1.4.120 /t 60 /c «This PC will restart in one minute for maintenance.» /f. If no one is using the computer, you can immediately send a command that restarts the device. Here’s an example: shutdown /r /m \\10.1.4.120 /t 0 /f
Once you complete the steps, the remote host will power off according to the command configuration.
If you want to disconnect from the IPC$ share, run the following command: «net use * /delete» (without quotations) and press Y to confirm. If you plan to use this command, you may need to remap previously connected network drives.
How to restart computer with shutdown command
To restart a Windows 10 device with Command Prompt, use these steps:
- Open Start.
- Search for Command Prompt, right-click the top result, and select the Run as administrator option.
- Type the following command to restart the device and press Enter: shutdown /r
- Type the following command to restart the device after a specific time and press Enter: shutdown /r /t TIME
In the command, replace TIME for the second to wait before the device begins the restart process. For example, this command restarts the computer after five seconds: shutdown /r /t 5
- Quick tip: You can also use «0» for the time to restart the device immediately.
- Type the following command to restart without waiting, or warning and press Enter: shutdown /r /p
- Type the following command to shut down, forcing all apps to close without warning, and press Enter: shutdown /r /f
After you complete the steps, the computer will restart according to the options you specified in the command.
How to sign out session with shutdown command
The shutdown tool also includes an option to sign out a user, but it is only available for the local computer, and you can only sign out of the current session. You cannot log off other users or someone on a remote device.
To log off of a Windows 10 account with Command Prompt, use these steps:
- Open Start.
- Search for Command Prompt, right-click the top result, and select the Run as administrator option.
- Type the following command to sign out of the current account session and press Enter: shutdown /L
Once you complete the steps, the current user session will be signed out.
How to hibernate computer with shutdown command
To put the computer into a hibernate state with a command, use these steps:
- Open Start.
- Search for Command Prompt, right-click the top result, and select the Run as administrator option.
- Type the following command to hibernate the device and press Enter: shutdown /h
After you complete the steps, the device will enter into the hibernation state. However, this only works on devices that support the feature. You can use these steps to enable and configure hibernation on Windows 10.
How to boot in firmware mode with shutdown command
The command-line tool even includes an option to start the computer into the Unified Extensible Firmware Interface (UEFI) or Basic Input Output System (BIOS) firmware without the need for extra steps.
To start the device in the UEFI or BIOS interface, use these steps:
- Open Start.
- Search for Command Prompt, right-click the top result, and select the Run as administrator option.
- Type the following command to restart the device into the firmware and press Enter: shutdown /r /fw
- Type the following command to shut down the computer and boot into the firmware during the next startup and press Enter: shutdown /s /fw
Alternatively, you can also use the /p instead of the /s option to close all running applications and force the shutdown without warning.
Once you complete the steps, the computer will boot into the firmware interface.
How to access the Advanced boot options with shutdown command
The «Advanced boot options» experience is the environment that includes various tools to troubleshoot and fix problems on Windows 10. Although you can use the Settings app or the USB flash drive to access these tools, you can also get into this experience with one shutdown command.
To start the computer in the Advanced boot options, use these steps:
- Open Start.
- Search for Command Prompt, right-click the top result, and select the Run as administrator option.
- Type the following command to restart the device into the Advanced boot options experience and press Enter: shutdown /r /o
- Type the following command to shut down the computer and start the Advanced boot options experience during the next startup and press Enter: shutdown /s /o
Alternatively, you can also use the /p instead of the /s option to close all running applications and force the shutdown without warning.
After you complete the steps, the computer will start in the Advanced boot tools, allowing you to access recovery tools to troubleshoot and fix the installation.
How to abort computer power off operation with shutdown command
This option is only available when using the time-out option on a remote computer. If the computer is scheduled to shut down after a specific period, you can abort the process.
To abort a shutdown, use these steps:
- Open Start.
- Search for Command Prompt, right-click the top result, and select the Run as administrator option.
- Type the following command to abort the shutdown and press Enter: shutdown /a /m \\REMOTE-PC
In the command, replace REMOTE-PC with the name or IP address of the remote computer. For example, this command aborts the shutdown action on the remote computer: shutdown /a /m \\10.1.4.120
In these steps, it is assumed you successfully ran the shutdown command, meaning you did the steps to configure the local computer and remote devices to allow the remote command execution (see above instructions).
We are focusing this guide on Windows 10, but the command-line tool has been available for a long time, which means you can refer to these instructions if you are still using Windows 8.x. Shutdown.exe is also available for Windows 7, but the options are limited. For example, the /o and /hybrid options are available starting on Windows 8.
More resources
For more helpful articles, coverage, and answers to common questions about Windows 10, visit the following resources:
- Windows 10 on Windows Central – All you need to know
- Windows 10 forums on Windows Central
Cutting-edge operating system
A refreshed design in Windows 11 enables you to do what you want effortlessly and safely, with biometric logins for encrypted authentication and advanced antivirus defenses.
All the latest news, reviews, and guides for Windows and Xbox diehards.
Mauro Huculak is technical writer for WindowsCentral.com. His primary focus is to write comprehensive how-tos to help users get the most out of Windows 10 and its many related technologies. He has an IT background with professional certifications from Microsoft, Cisco, and CompTIA, and he’s a recognized member of the Microsoft MVP community.
Several commands are available in Windows that allow you to shutdown or restart a local or remote computer. In this article, we’ll look at how to use the shutdown command and the PowerShell cmdlets Restart-Computer and Stop-Computer to shutdown/restart Windows.
Contents:
- Using the Shutdown Command on Windows
- How to Shutdown or Restart a Remote Windows Computer?
- Restart or Shutdown Windows with PowerShell
Using the Shutdown Command on Windows
The Shutdown.exe is a built-in Windows command line tool that allows to reboot, shutdown, put your computer to sleep, hibernate, or end a user session. In this guide, we’ll show the basic examples of using the shutdown command in Windows. All commands discussed above are run in the Run dialog box — Win+R
->, in the command prompt (cmd.exe) or in PowerShell.
The shutdown command has the following syntax: shutdown [/i | /l | /s | /r | /g | /a | /p | /h | /e | /o] [/hybrid] [/soft] [/fw] [/f] [/m \\computer][/t xxx][/d [p|u:]xx:yy [/c "comment"]]
As you can see, the command has quite a lot of options and can be used to shutdown/restart a local or remote computer.
How to shutdown windows from the command prompt?
To shutdown Windows, use the shutdown command with the /s key.
shutdown /s
Reboot Windows from the CMD
In order to reboot your computer, use the /r parameter. After running it, Windows will be will gracefully restarted.
shutdown /r
End a User Session
To end the current user session (logoff), run this command
shutdown /l
This command works in the same way as logoff.exe command.
How to hibernate Windows using the shutdown command?
To hibernate your computer, run this command:
shutdown /h
In the hibernate mode, all the contents of memory are written to the hiberfil.sys file on the local disk and the computer goes into sleep mode with reduced power consumption.
Notify logged-in users of an impending reboot or shutdown
You can notify all logged-on Windows users about the upcoming shutdown/reboot of the computer or server by sending a pop-up message to all active sessions. As a rule, this feature is used on RDS servers with several users working on them at the same time in their own RDP sessions.
shutdown /r /c “This server will be restarted in 60 seconds.”
Delayed shutdown/reboot of a computer using the timer
You can shutdown or restart the computer with a certain delay (on a timer). Using the /t option, you can specify the time span after which the computer/server will be shutdown or rebooted. Thus you can provide your users some time to save open files and close the apps correctly. It is convenient to use this option together with the notification message. In this example, we inform the users that Windows will be shutdown in 10 minutes (600 seconds).
shutdown /s /t 600 /c "The server will be shutdown in 10 minutes. Save your work!"
A user will be warned about the scheduled shutdown:
You’re about to be signed out
If the delay is too long (for example, 60 minutes/3,600 seconds), a pop-up window appears in the lower right corner of the screen:
You’re about to be signed out. Your Windows will shutdown in 100 minutes.
How to stop/cancel/abort system shutdown in Windows
Windows waits 60 seconds by default without doing anything after running shutdown or reboot command. An administrator can cancel the restart or shutdown of the device by running this command during this time:
shutdown /a
After you cancel the shutdown, you’ll see the following pop-up message in the lower right corner of the screen:
Logoff is cancelled. The scheduled shutdown has been cancelled.
Restart Windows immediately
To shutdown or reboot a computer immediately without waiting for 60 seconds, specify 0 as a value of the /t parameter. For example:
shutdown /r /t 0
The /f key is very important. I use it almost always when shutting down or restarting Windows Server hosts. This attribute allows to force close all running programs and processes without waiting for confirmation from the user (we won’t wait till the users confirm closing all applications on the RDS server since we can never get it).
The next command will restart the computer and automatically run all registered apps after reboot (apps registered in the system using RegisterApplicationRestart API are meant here).
shutdown /g
Create a restart shortcut on Windows Desktop
To make it more convenient for users, you can create a desktop shortcut to restart or shutdown a computer with the required parameters. Such a shortcut may be useful when you need to restart the computer from the RDP session when there are no options to restart or shutdown the computer in the Start menu.
How to restart Windows at a specific time (on schedule)?
If you want your computer or server to restart/shutdown at a specific time, you can add the shutdown command with the parameters to Windows Task Scheduler (taskschd.msc
).
For example, this Scheduler task will restart the computer daily at 12 AM.
Or you can create a new Scheduler task with PowerShell:
$Trigger= New-ScheduledTaskTrigger -At 00:00am -Daily
$User= "NT AUTHORITY\SYSTEM"
$Action= New-ScheduledTaskAction -Execute "shutdown.exe" -Argument "–f –r –t 120"
Register-ScheduledTask -TaskName "RebootEvertyNight_PS" -Trigger $Trigger -User $User -Action $Action -RunLevel Highest –Force
How to Shutdown or Restart a Remote Windows Computer?
You can use the shutdown.exe command to reboot a remote computer. To do this, the remote computer must be accessible over the network, and the account u you are using must be a member of the local Administrators group on the remote computer (server):
shutdown /r /t 120 /m \\192.168.1.210
If all the conditions described above are met, but when running the shutdown command the error “Access denied (5)” appears, you need to allow remote access to the administrative shares (C$, ADMIN$) on the remote computer by changing the value of LocalAccountTokenFilterPolicy parameter to 1.
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v "LocalAccountTokenFilterPolicy" /t REG_DWORD /d 1 /f
If you need to provide user credentials to connect to a remote computer, you can use the commands:
net use \\192.168.13.111 /u:corp\username
shutdown /s /t 60 /f /m \\192.168.13.111
If you need to restart multiple computers remotely, you can save the list of computers to a text file, and start a remote reboot of all computers using a simple PowerShell script:
$sh_msg = "Your computer will be automatically restarted in 10 minutes. Save your files and close running apps"
$sh_delay = 600 # seconds
$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"
}
Restart multiple computers with a Shutdowm.exe GUI
For those who don’t feel comfortable working in the command prompt, there is a graphical interface for the shutdown.exe command. To call the Remote Shutdown Dialog GUI, use the command:
shutdown /i
As you can see, you can add multiple computers in the remote shutdown dialog to be rebooted/shutdown, specify the notification text and specify the reason for the shutdown to be saved in the Windows event log.
Restart or Shutdown Windows with PowerShell
The following two commands are available in Windows PowerShell to shutdown and reboot the computer: Restart-Computer and Stop-Computer. Both commands allow you to shutdown or restart a local or remote computer (over the network).
To restart Windows, run:
Restart-Computer -force
To shutdown your computer:
Stop-Computer
By default, the reboot will start in 5 seconds. You can increase the delay before reboot:
Restart-Computer –Delay 60
Both cmdlets have a -ComputerName
parameter that allows you to specify a list of remote computers to perform the action on.
For example, to shutdown two Windows servers remotely:
Stop-Computer -ComputerName "mun-srv01", "mun-srv02"
You can specify administrator credentials to connect to a remote host:
$Creds = Get-Credential
Restart-Computer -ComputerName mun-srv01-Credential $Creds
WMI and DCOM are used to connect to remote computers (they must be enabled and configured). If WMI is not configured, the following error will appear when running the command:
Restart-Computer : Failed to restart the computer wks-11222 with the following error message: Access is denied. Exception from HRESULT: 0x80070005 (E_ACCESSDENIED).
If WinRM (Windows Remote Management) is enabled on the remote computer, you can use WSman instead of WMI to connect:
Restart-Computer -ComputerName wks-11222 -Protocol WSMan
If there are active user sessions on the remote computer, an error will appear:
Restart-Computer : Failed to restart the computer wks-11222 with the following error message: The system shutdown cannot be initiated because there are other users logged on to the computer.
To force a reboot, you need to add the -Force parameter:
Restart-Computer -ComputerName wks-11222 –Force
You can use the -For
option to restart your computer and wait until it becomes available. For example, you want to make sure that the remote computer reboots successfully and the WinRM service is started on it, allowing you to connect to it through WS-Management:
Restart-Computer -ComputerName wks-11222 -Wait -For WinRM
Restarting computer wks-11222 Verifying that the computer has been restarted.
You can wait for the Remote Desktop Service (RDP) or any other Windows service to start:
Restart-Computer -ComputerName wks-11222 -Wait -For TermService
If you need to restart multiple computers at the same time, you can use the parallel command execution available in PowerShell 7.x (see how to update PowerShell).
For example, you can get a list of Windows Servers hosts in a specific Active Directory container (Organizational Unit) using the Get-ADComputer cmdlet and restart them at the same time:
$Computers = (Get-ADComputer -Filter 'operatingsystem -like "*Windows server*" -and enabled -eq "true"' -SearchBase "OU=Servers,DC=woshub,DC=com").Name
$Computers | ForEach-Object -Parallel { Restart-Computer -ComputerName $_ -Force} -ThrottleLimit 3
Updated: 04/02/2019 by
The shutdown command lets you shut down a Windows computer from the command line. It also has additional features that are not available in Windows.
Availability
Shutdown is an external command available for the following Microsoft Windows operating systems as shutdown.exe.
- Windows XP
- Windows Vista
- Windows 7
- Windows 8
- Windows 10
- Windows 11
Shutdown syntax
- Windows 10 and 11 syntax
- Windows 8 syntax
- Windows Vista and 7 syntax
- Windows XP syntax
Windows 10 and 11 syntax
shutdown [/i | /l | /s | /sg | /r | /g | /a | /p | /h | /e | /o] [/hybrid] [/soft] [/fw] [/f] [/m \\computer][/t xxx][/d [p|u:]xx:yy [/c "comment"]]
No args | Display help. Same as typing /?. |
/i | Display the GUI (graphical user interface). Must be the first switch used in the command. |
/l | Log off. The /l switch cannot be used with /m or /d options. |
/s | Shutdown the computer. |
/sg | Shutdown the computer. On the next boot, if Automatic Restart Sign-On is enabled, automatically sign in and lock the last interactive user. |
/r | Full shutdown and restart the computer. |
/g | Full shutdown and restart the computer. After the system is rebooted, if Automatic Restart Sign-On is enabled, automatically sign in and lock the last interactive user. |
/a | Abort a system shutdown. It can only be used during the time-out period. |
/p | Turn off the local computer with no time-out or warning. It can be used with /d and /f options. |
/h | Hibernate the local computer. It can be used with the /f option. |
/hybrid | Performs a shutdown of the computer and prepares it for fast startup. Must be used with /s option. |
/fw | Combine with a shutdown option to cause the next boot to go to the firmware user interface. |
/e | Document the reason for an unexpected shutdown of a computer. |
/o | Go to the advanced boot options menu and restart the computer. Must be used with /r option. |
/m \\computer | Specify the target computer. |
/t xxx | Set the time-out period before shutdown to xxx seconds. The valid range is 0-315360000 (10 years), with a default of 30. If the timeout period is greater than 0, the /f parameter is implied. |
/c «comment» | Comment on the reason for the restart or shutdown. A maximum of 512 characters is allowed. |
/f | Force running applications to close without forewarning users. The /f parameter is implied when a value greater than 0 is specified for the /t parameter. |
/d [u] [p]:xx:yy | Provide the reason for the restart or shutdown.
p — indicates that the restart or shutdown is planned. If neither p nor u is specified, the restart or shutdown is unplanned. xx — is the major reason number (positive integer less than 256). |
Windows 8 syntax
shutdown [/i | /l | /s | /r | /g | /a | /p | /h | /e | /o] [/hybrid] [/f] [/m \\computer][/t xxx][/d [p|u:]xx:yy [/c "comment"]]
No args | Display help. Same as typing /?. |
/i | Display the GUI (graphical user interface). Must be the first switch used in the command. |
/l | Log off. Note: The /l switch cannot be used with /m or /d options. |
/s | Shutdown the computer. |
/r | Full shutdown and restart the computer. |
/g | Full shutdown and restart the computer. After the system is rebooted, restart any registered applications. |
/a | Abort a system shutdown. But can only be used during the time-out period. |
/p | Turn off the local computer with no time-out or warning. Can be used with /d and /f options. |
/h | Hibernate the local computer. Can be used with the /f option. |
/hybrid | Performs a shutdown of the computer and prepares it for fast startup. Must be used with /s option. |
/e | Document the reason for an unexpected shutdown of a computer. |
/o | Go to the advanced boot options menu and restart the computer. Must be used with /r option. |
/m \\computer | Specify the target computer. |
/t xxx | Set the time-out period before shutdown to xxx seconds. The valid range is 0-315360000 (10 years), with a default of 30. If the timeout period is greater than 0, the /f parameter is implied. |
/c «comment» | Comment on the reason for the restart or shutdown. Maximum of 512 characters allowed. |
/f | Force running applications to close without forewarning users. The /f parameter is implied when a value greater than 0 is specified for the /t parameter. |
/d [u] [p]:xx:yy | Provide the reason for the restart or shutdown.
Options: p — Indicates that the restart or shutdown is planned. If neither p nor u is specified, the restart or shutdown is unplanned. Reasons: xx — Is the primary reason number (positive integer less than 256). |
Windows Vista and 7 syntax
shutdown [/i | /l | /s | /r | /g | /a | /p | /h | /e] [/f] [/m \\computer] [/t xxx][/d [p|u:]xx:yy [/c "comment"]]
No args | Display help. Same as typing -?. |
/i | Display the GUI (graphical user interface). Must be the first switch used in the command. |
/l | Log off. The /l switch cannot be used with /m or /d options. |
/s | Shutdown the computer. |
/r | Shutdown and restart the computer. |
/g | Shutdown and restart the computer. After the system is rebooted, restart any registered applications. |
/a | Abort a system shutdown during the time-out period. |
/p | Turn off the local computer with no time-out or warning. It can be used with /d and /f options. |
/h | Hibernate the local computer. It can be used with the /f option. |
/e | Document the reason for an unexpected shutdown of a computer. |
/m \\computer | \\computer Specify the target computer. |
/t xxx | Set the time-out period before shutdown to xxx seconds. The valid range is 0-315360000 (10 years), with a default of 30. If the timeout period is greater than 0, the /f parameter is implied. |
/c «comment» | Comment on the reason for the restart or shutdown. A maximum of 512 characters is allowed. |
/f | Force running applications to close without forewarning users. The /f parameter is implied when a value greater than 0 is specified for the /t parameter. |
/d [u] [p]:xx:yy | Provide the reason for the restart or shutdown.
Options: p — Indicates that the restart or shutdown is planned. If neither p nor u is specified, the restart or shutdown is unplanned. Reasons: xx — Is the primary reason number (positive integer less than 256). |
Windows XP syntax
shutdown [-i | -l | -s | -r | -a] [-f] [-m \\computername] [-t xx] [-c "comment"] [-d up:xx:yy]
No args | Display help. Same as typing -?. |
-i | Display GUI interface, must be the first option. |
-l | Log off (cannot be used with -m option). |
-s | Shutdown the computer. |
-r | Shutdown and restart the computer. |
-a | Abort a system shutdown. |
-m \\computername | Remote computer to shutdown/restart/abort. |
-t xx | Set timeout for shutdown to xx seconds. |
-c «comment» | Shutdown comment (maximum of 127 characters). |
-f | Forces running applications to close without warning. |
-d [u] [p]:xx:yy | The reason code for the shutdown. u — is the user code. p — is a planned shutdown code. xx — is the major reason code (positive integer less than 256). yy — is the minor reason code (positive integer less than 65536). |
Shutdown examples
Note
The earlier version of the shutdown command uses a dash (-) instead of a forward slash (/) for its options.
shutdown -r -c "Rebooting for latest updates."
This command would display a Windows system shutdown window for 30 seconds. This window would warn the user that the computer shuts down and then restarts the computer.
shutdown -i
Ran from either the command line or from the Windows run line, this option would open the remote shutdown dialog window.
shutdown /h
Place the computer in hibernation mode in Windows.
shutdown /l
Immediately logs off the current user in Windows.
shutdown /s /t 60
Shuts down the computer after 60 seconds.
shutdown /s /m \\PC123 /t 20
Shuts down remote computer name «PC123» after 20 seconds.
shutdown /s /t 45 shutdown /a
The first command initiates a computer shutdown after 45 seconds. The second command aborts the shutdown if it’s executed in the shutdown timeout period, which is 45 seconds in this example.
-
Home
-
News
- How to (Remotely) Shut Down Windows 10 with CMD Command Line
By Alisa |
Last Updated
To shut down Windows 10 PC, one quick way is to use Command Prompt commands. Check how to shutdown Windows 10 using command line in CMD. Also learn how to remotely shut down a Windows 10 PC with CMD. As the best Windows 10 software mate, MiniTool software also provides you data recovery, hard drive management, system backup and restore tools.
- What is the command for Windows 10 shutdown in CMD?
- How do I shut down Windows 10 from Command Prompt?
- How do I shut down a computer remotely with Command Prompt?
If you meet Windows 10 won’t shut down problem by using the usual ways, you can try the unusual way to shut down your Windows 10 PC. Learn how to shut down Windows 10 with command line in CMD (Command Prompt) below. This is helpful when computer freezes, gets stuck or crashes because of some errors and can’t shut down. (Related: How to Repair Windows 10)
How to Shut Down Windows 10 with Command Line in CMD
Step 1. You can press Windows + R, type cmd, and press Enter to open Command Prompt in Windows 10.
Step 2. In Command Prompt window, you can type shutdown /s command line, and hit Enter, then the CMD.exe will perform the Windows shutdown action.
Tip: You can also type shutdown command in CMD after you enter into Command Prompt window, and it will present a list of different options for Windows 10 shutdown. Different command lines perform different operations. You can check some of the Windows shutdown commands below.
- shutdown /s – just shut down your Windows 10 computer.
- shutdown /r – shut down and restart the computer.
- shutdown /a – abort the system shutdown before the timeout.
- shutdown /l – log off the computer.
- shutdown /f – force close running applications without forewarning users.
- shutdown /m \\computername – specify the target computer you want to shut down.
- shutdown /t xxx – set the timeout period before shutdown to xxx seconds. (Related: schedule shutdown Windows 10)
- shutdown /c “comment” – comment on the reason for the restart or shutdown.
Windows 10 Shutdown Shortcut
Some of you may also wonder how to use keyboard shortcut to shut down Windows 10. You can press Alt + F4, and it will pop up the Shutdown dialog. You can then use the arrow keys on the keyboard to select an option and press Enter to power off Windows 10 PC or laptop.
How to Remotely Shut Down or Restart a Windows 10 Computer with CMD
You can even use Command Prompt to remotely restart or shut down a Windows 10 computer over the Internet. The Windows PCs should be connected to the same network.
After you enter into Command Prompt, you can type shutdown /m \\computername /r /f command line, and hit Enter. This will remotely restart the target Windows 10 computer and force close all running programs on it.
To shut down a Windows 10 computer remotely, you can type the command line: shutdown /m \\computername /s /c “This computer will shut down, please save all work.” /t 100, and hit Enter. This command line will shut down Windows 10 computer in CMD, along with forcing all running programs to close, show the warning message, and count down 100 seconds before the remote computer shuts down.
You can also remotely shutdown PC via Shutdown dialog.
- You can type shutdown /i command in CMD, and press Enter to open Remote Shutdown Dialog.
- Click Add or Browse button to add the target computers to the list. You can type the computer network name in \\computername format or just type the computer name.
- Then you can set the shutdown options: restart or shutdown. You can also set the shutdown settings like displaying a warning.
- Then you can run the corresponding Windows shutdown commands to shut down or restart a batch of computers in the same network.
Bottom Line
This post gives some tips on how to shut down Windows 10 with command line in CMD, and how to how to restart or shut down remote computers with CMD. If you have better ideas, please do not hesitate to share with us.
About The Author
Position: Columnist
Alisa is a professional English editor with 4-year experience. She loves writing and focuses on sharing detailed solutions and thoughts for computer problems, data recovery & backup, digital gadgets, tech news, etc. Through her articles, users can always easily get related problems solved and find what they want. In spare time, she likes basketball, badminton, tennis, cycling, running, and singing. She is very funny and energetic in life, and always brings friends lots of laughs.