Когда сервер Windows работает в течение длительного периода времени, приложения и функции операционной системы могут работать нестабильно. Нестабильная операционная система может иметь сбои приложений, зависание приложений или утечки памяти. Иногда даже важные системные функции перестают отвечать.
Простым решением является перезагрузка. В этом руководстве вы узнаете, как перезапустить Windows Server 2016 с несколькими параметрами команды.
Перезагрузить Windows Server через графический интерфейс
Интерфейс Windows Server 2016 представляет собой графический интерфейс, который упрощает многие задачи.
Нажмите: меню Пуск -> Кнопка питания -> Перезагрузить.
Как перезагрузить Windows Server с помощью командной строки
В некоторых случаях у вас может не быть установлен компонент GUI. Или ваша операционная система столкнулась с проблемой, и все, что вы можете получить доступ, это командная строка.
Шаг 1: Откройте командную строку
- Нажмите Ctrl + Alt + Del.
- Система должна показать меню — щелкните Task Manager (Диспетчер задач).
- В окне Task Manager (Диспетчер задач) нажмите More Details (Подробнее).
- Откройте меню File (Файл) и выберите Run new task (Запустить новое задание).
- В поле введите
cmd.exe–
, затем установите флажок, чтобы создать задачу с правами администратора. Нажмите ОК. - Должно появиться черное окно с белым текстом.
Шаг 2. Перезагрузите операционную систему Windows Server.
В окне командной строки введите команду перезагрузки Windows Server и нажмите клавишу Enter:
shutdown –r
Параметр –r
заставляет Windows перезагружаться, а не просто выключаться.
Перезапуск из PowerShell
Windows PowerShell напоминает расширенную версию командной строки. Он основан на .NET Framework и включает язык сценариев. PowerShell полезен для работы под операционной системой Windows.
Шаг 1. Запустите PowerShell
- Нажмите Ctrl + Alt + Del и выберите Task Manager (Диспетчер задач).
- Откройте меню File (Файл) и выберите Run new task (Запустить новое задание).
- В командной строке введите
powershell.exe
и установите флажок, чтобы начать с правами администратора. Нажмите ОК. - Должно открыться новое окно с темно-синим фоном. Вы можете понять, что находитесь в окне PowerShell, если подсказка начинается с
PS
.
Шаг 2: перезагрузите систему
В окне PowerShell введите следующую команду и нажмите Enter:
Restart-Computer
По умолчанию вы получите 5-секундный обратный отсчет, затем система перезагрузится. Вы можете добавить опцию, чтобы отложить перезапуск на более чем 5 секунд по умолчанию:
Restart-Computer –delay 15
Перезагрузка удаленного сервера Windows с помощью PowerShell
Шаг 1. Запустите PowerShell
Если вы находитесь в командной строке, введите команду:
PowerShell
Подсказка добавит PS
в начале, и ваши набранные команды должны появиться в желтом цвете.
Шаг 2. Перезагрузитесь удаленно
В окне PowerShell введите следующее:
Restart-Computer –ComputerName “NAME_OF_SYSTEM”
Замените NAME_OF_SYSTEM
на имя компьютера, который вы хотите перезагрузить. Не забудьте поставить кавычки.
Примечание. Предполагается, что ваши текущие учетные данные те же, что и для удаленной системы. Обычно это может выглядеть как имя пользователя администратора, и один и тот же пароль для обеих систем. Это также может работать, если обе системы находятся в одном домене, а ваша учетная запись пользователя имеет соответствующие разрешения.
Restarting a Windows Server is crucial for applying updates, troubleshooting issues, and maintaining system performance. Regular restarts help ensure a server runs the latest software, resolves conflicts, and clears temporary files.
This tutorial explains how to restart a Windows server using different methods.
Prerequisites
- A system running Windows Server.
- Access to the Command Prompt.
- Access to PowerShell.
Why Restart a Windows Server?
Restarting a Windows server is essential for applying critical updates and patches that enhance security and performance. It helps resolve software conflicts and clears out temporary files, which improves system stability and speed. It also closes running processes that slow the system down and starts them up again. Restarting is also helpful in troubleshooting network connectivity issues and application errors.
Note: A full Windows server restart clears all processes, ensuring a fresh start. However, using Fast Boot reduces downtime by speeding up the startup process. Still, Fast Boot only applies after a complete shutdown, never when restarting the system. Fast Boot is also more relevant to client versions of Windows, while server environments often prioritize full resets for stability and performance. So, use Fast Boot for personal computers or lightweight server tasks and avoid it for critical servers, troubleshooting, and security-sensitive environments. To set up Fast Boot, access Power Options in Windows settings.
Shutdown vs. Restart
Restarting a Windows server closes all applications and processes, shuts down the system, and immediately powers it back on, ensuring a complete reset of all system components. However, shutting down powers it off completely.
Use shutdown for regular power-offs, especially when Fast Boot is enabled for faster startups. Use restart when applying updates, troubleshooting, or needing a complete system reset to clear temporary issues.
Soft vs. Hard Restart
A soft restart is the standard method for restarting Windows. It involves using the operating system’s built-in restart command or restarting through the Start menu, which closes all running applications and processes before restarting the system.
On the other hand, a hard restart, also known as a hard reboot or force restart, involves forcibly cutting power to the system by holding down the power button until the system shuts down or disconnecting the power source and then turning it back on again. This method is used when the system becomes unresponsive and cannot be restarted using the usual soft restart method.
How to Restart a Windows Server
There are several ways to restart a Windows server, such as the Command Prompt, PowerShell, or via the GUI. The following text presents a few ways to do that.
Note: Save all work before restarting your server to avoid losing any data or halting the process.
Restart the Windows Server with the GUI
The Windows Graphical User Interface simplifies many tasks, including restarting servers. To restart the Windows server via GUI, take the following steps:
1. Click the Start menu.
2. Select the Power button.
3. Click Restart.
Restart Windows Server via Command Prompt
If the GUI is not installed or working, other options exist for restarting your Windows server. One of them is to use the Windows shutdown
command. The Windows shutdown
command allows you to shut down, restart, log off, or hibernate your computer from the command line. Its syntax is:
shutdown [options]
The shutdown
command has plenty of options, but the one relevant to this tutorial is -r
. The –r
option tells Windows to restart instead of shutting down.
To restart the Windows server, access the Command Prompt and enter:
shutdown –r
The command has no output, but it restarts the server.
Restart Windows Server via Windows Powershell
PowerShell is a robust command-line shell developed by Microsoft. It’s designed for system administration tasks, automation, and managing configurations across Windows-based systems.
The Restart-Computer
cmdlet in PowerShell is used to restart a computer. It provides options to specify the computer name, force the restart, wait for the restart to complete, add a delay before the restart, set a timeout period, and provide credentials if necessary. The command syntax with all available options is:
Restart-Computer [-ComputerName] [-Force] [-Wait] [-For ] [-Delay ] [-Timeout ] [-Credential ] [-Protocol ] [-Confirm] [-WhatIf]
The command consists of:
[-ComputerName]
. Specifies the name of the computer to restart.[-Force]
. Forces the restart without prompting for confirmation.[-Wait]
. Waits for the restart to complete before returning.[-For]
. Specifies how long it takes for the restart to complete (in seconds).[-Delay]
. Specifies a delay before initiating the restart (in seconds).[-Timeout]
. Specifies a timeout period for the restart operation (in seconds).[-Credential]
. Shows a user account with permission to restart the computer.[-Protocol]
. Determines the protocol to use for the restart operation.[-Confirm]
. Prompts for confirmation before executing the restart.[-WhatIf]
. Shows what happens if the restart command runs without actually restarting the computer.
To restart a server, use the command without any options. Access the PowerShell and type the following:
Restart-Computer
You can delay the restart for longer than the default five seconds. For example, delay the restart for 15 seconds with:
Restart-Computer –delay 15
Restart Remote Windows Server
Use PowerShell to restart a remote Windows server. In the PowerShell window, type the following:
Restart-Computer –ComputerName ["NAME_OF_SYSTEM"]
Replace ["NAME_OF_SYSTEM"]
with the name of a server you want to restart. Make sure to include the quotation marks. For example, to restart a remote machine named «Server01», run the following:
Restart-Computer -ComputerName "Server01"
This command initiates a restart of the remote Windows server named «Server01».
Conclusion
Restarting a Windows server is simple, and this article presents several different ways to do it.
Next, learn about the most important Windows cmd commands.
Was this article helpful?
YesNo
As a system administrator, one of the essential skills you need to master is the ability to efficiently manage and troubleshoot servers. This includes knowing how to restart a Windows Server using command-line tools. This article delves into various methods and tricks to restart Windows Server using the command line, a crucial technique for quick and effective server management.
To reboot a Windows server using the command line, you can employ the /r
switch with the shutdown
command. This article provides various examples of how to use command line instructions to restart Windows systems.
- Restart Computer: For restarting a local Windows system, use the following command:
shutdown /r
- Restart Forecefully: To restart the local system and force all running applications to close, include the
/f
switch:shutdown /r /f
- Adding a Timer: Optionally, you can add a delay to the restart process. For instance, below command will restart the server after 60 seconds.
shutdown /r /t 60
- Restart Remote Computer: If you need to restart a remote system, include the system’s hostname with the
/m
switch:shutdown /r /f /m \\REMOTE-PC
- Adding Comments: Additionally, you can add a comment to document the reason for the reboot using the
/c
switch. For instance, if you are restarting the system after installing software, the command would be:shutdown /r /f /m \\REMOTE-PC /c "Post Installing Software"
These commands offer a streamlined and efficient way to manage system restarts directly from the command line.
Using PowerShell
For those who prefer PowerShell, the process is similar but uses different commands:
- Open PowerShell: Search for it in the start menu or type powershell in the Run dialog.
- Restart-Computer Command: Use the command
Restart-Computer
. This straightforward command initiates an immediate restart of the server.Restart-Computer
- Adding Parameters: Similar to Command Prompt, you can add parameters like
-Delay
to set a timer for the restart.Restart-Computer -Delay 60
- Restart Remote Server: If you need to restart a server remotely, you can use the following command in PowerShell:
Restart-Computer -ComputerName [ServerName] -Force
Replace
[ServerName]
with the actual name of the server. The-Force
parameter ensures that all running applications are closed immediately.
Conclusion
Mastering the command line for restarting Windows Server is a vital skill for any system administrator. It provides a quick, reliable, and scriptable method to manage servers, especially in complex or remote environments. By incorporating these tips and tricks into your routine, you can significantly streamline your server management tasks.
Remember, while the command line is a powerful tool, always proceed with caution and ensure you have backups and a recovery plan in place for unforeseen circumstances.
В 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
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.