There will be times as a Windows Administrator when you will need to reboot or shutdown a remote computer or server.
In this tutorial, I’ll show you two easy methods for rebooting and shutting down remote computers.
The first method uses a built in Windows command and the second method uses PowerShell.
Check it out.
Windows Remote Shutdown Command
Windows systems have a built in shutdown command that can be used to restart or shutdown local and remote computers.
The command is shutdown.
To use this command just open the windows command prompt and type shutdown.
To view the full list of command options type shutdown /? in the CMD window.
There are several command line switches, below I list the most useful options.
/s – Shutdown the computer
/r – restart computer
/m \\computer – Specify the remote computer
/l – Log off
/t xxx – Set the time out period before shutdown to xxx seconds
/c “comment” – Message to display on the screen before restart or shutdown
Now let’s move on to some examples
Remote Desktop Connection Manager | Remote Session Tools
Download 14 day Free Trial
Restart or Shutdown Examples with Command Line
In these examples, I’ll be on PC1 and will initiate a remote restart or shutdown on PC2.
I’ll be using the /r switch in these examples, you can change them to /s to shutdown instead of restart.
Example 1: Restart Remote Computer
By default, this will prompt the remote computer and give it about a minute before it restarts.
shutdown /r /m \\pc2
The pop up below is what a Windows 10 system will display.
Example 2: Restart With a Custom Message
You may want to display a custom message to the logged on users, to do that just use the /c command.
shutdown /m \\pc2 /c "The IT department has initiated a remote restart on your computer"
Below is the pop up on the remote computer with the custom message.
Example 3: Immediate Restart no Countdown
If you want to immediately restart with no countdown or message use this command.
shutdown /r /m \\pc2 /t 0
If you want a longer countdown just specify the seconds /t 60
Example 4: Log user off the remote computer
If you just want to log a user off the remote computer use this command.
shutdown /l /m\\pc2
Restart or Shutdown the Computer with Powershell
Here are a few examples of how you can restart or shutdown computers with PowerShell.
The downside to PowerShell is it doesn’t have as many options as the shutdown command. There is no option to prompt users with a custom message or provide a countdown.
Example 1: Use Powershell to restart a computer
This command will immediately restart a remote computer. The -Force option will force a restart even if a user is logged on.
Restart-Computer -ComputerName REMOTE_COMPUTER_NAME -Force
Example 2: Use PowerShell to shutdown a computer
This command will shutdown a remote computer. Use the -Force to force a shutdown even if a user is logged on.
Stop-Computer -ComputerName REMOTE_COMPUTER_NAME -Force
Example 3: Use PowerShell to restart a list of computers
This is handy if you have several computers to restart. Just list all the computers you want in a text file and add that to the PowerShell command.
restart-computer (get-content c:\work\computers.txt)
Example 4: Use PowerShell to shutdown down two computers
Stop-Computer -ComputerName "Server01", "Server02"
Want an easy way to check windows server uptime and last boot date on all computers? Then check out the tool below.
The AD Pro Toolkit includes 13 tools to simplify Active Directory and computer management. Download a free trial and try it for yourself.
I hope you found this article useful. If you have questions or comments leave them below. You might also like to check out my guide on How to Remotely Log off Windows Users.
using COMMAND Line
1. Login with a full administrative account to another computer.
2. Open a Command Prompt (CMD) window.
3. Type the following command:
Example 1: Restart a remote server
Shutdown /m \\servername /r
Example 2: Restart a remote server immediately
Shutdown /r /m \\servername /t 0
If you want to delay the restart, specify the seconds: e.g. /t 60
Example 3: Restart the remote server with a custom message
Shutdown /m \\servername /c «The server will restart for maintenance purpose»
Example 4: Log off a user on a remote server
shutdown /l /m \\servername
using POWERSHELL
1. Login with a full administrative account to another computer.
2. Open a Powershell window.
3. Type the following command:
Example 1: Use Powershell to restart a remote server immediately
Restart-Computer -ComputerName REMOTE_COMPUTER_NAME -Force
Example 2: Use PowerShell to shut down a remote server
Stop-Computer -ComputerName REMOTE_COMPUTER_NAME -Force
Example 3: Use PowerShell to restart a list of servers
Restart-computer (get-content c:\serverslist.txt)
Example 4: Use PowerShell to shutdown multiple remote servers
Stop-Computer -ComputerName «Servername01», «Servername02»
If you are a Windows Administrator and responsible for managing hundreds or thousands of computers then you may often need to restart or shutdown multiple computers at a time. Performing this task manually will take lots of time. In this case, you can use tho methods to reboot or shutdown the remote computer.
In this guide, we will show you how to restart and shutdown the remote computers using command-line or PowerShell.
Restart or Shutdown with Command Line
In this section, we will show you how to use shutdown command to restart or shutdown the Windows computer with examples.
Basic Syntax
The basic syntax of the shutdown command is shown below
shutdown [option] "Computer Name"
A brief explanation of each option is shown below:
- /s : Used to restart the computer.
- /r : Used to shutdown the computer.
- /l : Used to log off the computer.
- /m \\computer : Used to specify the remote computer.
- /c “Message” : Used to specify the message to display on the remote computer screen before restart or shutdown.
- /t : Used to set the time period for restart or shutdown.
Restart the Local Computer
If you want to restart your own computer, run the following command:
shutdown /r
Restart the Multiple Computer with GUI
You can use the option /i with shutdown command to open a graphical interface to restart a single or multiple computers:
shutdown /i
You should see the following screen:
From here, you can add multiple remote computers and restart or shutdown them easily.
Restart the Remote Computer with Command Line
You can use the option /r and specify the remote computer name to display the prompt on the remote computer and give it a minute before it restarts.
shutdown /r /m \\computer-name
You can also use the /s option to shutdown the remote computer.
shutdown /s /m \\computer-name
Restart a Remote Computer with Message
You can also send a message on the remote computer screen before restart or shutdown it.
shutdown /r /m \\computer-name -c "The IT department has initiated a remote restart on your computer"
Shutdown a Remote Computer After Specified Time
You can use the option /t to shutdown a remote computer after a specific time.
For example, shutdown a remote computer after 10 seconds, run the following command:
shutdown /s /t 10
Restart or Shutdown the Remote Computer with PowerShell
You can shutdown or restart one or more computers easily with the Windows PowerShell. In this section, we will show you how to restart or shutdown the remote computer with PowerShell.
Restart a Single Computer with PowerShell
You can use the following command to restart the remote computer with PowerShell:
Restart-Computer -ComputerName computer-name -Force
Shutdown a Single Computer with PowerShell
You can also shutdown the remote computer using the Stop-Computer command:
Stop-Computer -ComputerName computer-name -Force
Restart Multiple Computers with PowerShell
If you want to shutdown the two computers, run the following command:
Restart-Computer -ComputerName "computer1", "Computer2"
Restart a Multiple COmputers with PowerShell
If you want to restart multiple computers then you can create a text file, add all computers in the file then specify this file path with Restart-Computer command to restart all computers listed inside the file.
Restart-Computer (get-content C:\computer-list.txt)
Conclusion
In the above guide, you learned how to restart and shutdown the remote computer with the PowerShell and command line. I hope you can now easily restart and shutdown the single or multiple remote computers.
В 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)
{
Invoke-Expression "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
Each Administrator has experienced at least one time that he can not access the server to restart it, except physically. This can be very frustrating, in this article, I will try to describe how to configure Windows Server 2008 R2 and Windwos Server 2012 for remote restart using the command prompt ( CMD ).
You can find various tutorials of this type on the Internet, but most of them are useless because it is not complete. This remote control option works on Windows Server 2008 and Windows Server 2012 OS. First, you need to go on the Control Panel – Network and Sharing Center, Change Advanced Sharing settings – Turn on file and printer sharing and Turn on network discovery.
After that, you type regedit.exe in the run, and after the window opens, go to the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System path and create a NEW – DWORD file named LocalAccountTokenFilterPolicy and assign it a value of 1 to look like in the picture below.
Since we have done the registry part, it is necessary to define which user will be able to access this type of server control. We do this by defining roles in Group Policy Management. On the Security Settings – Local Policies – User Rights Assignment, we need to edit Force shutdown from a remote system. On the Force shutdown tab from a remote system Properties we need to add a user or group that can access the server shutdown or restart remotely.
If everything is set up properly, we can start testing. Started Command Prompt with Administrator privileges on a computer that is on the same network as the server and then type the following commands:
net use \\serverip\ipc$ /user:domain\usename password
After typing the command, press Enter. If everything is OK, you will be seen a message
“The command complete successfully” after which, you can start using the shutdown option. Below you will find the most commonly used options and some examples how to use shutdown.
So for remotely shutting down another machine on your network, you would type into the command prompt the following commands:
shutdown /m \\computerip /r /f
This command will restart the computer and force all programs that are still running to close.
shutdown –m \\computerip –s –f –c “The computer will restart, please save all work.” –t 60
This command will shutdown the computer, force all programs that are running to close, show a message to the user and countdown 60 seconds before it shuts down.
Here are a couple of the most common command:
/s: Shuts down the computer
/r: Restarts the computer
/m \\computerip: The target remote computer to shut down
/f: Forces programs to close immediately
/t: Will wait a certain amount of time in seconds before shutting down or restarting
/c “comment”: This shutdown command option allows you to leave a comment describing the reason for the shutdown or restart.