В 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
Restarting a Windows Server 2016 from the Command Prompt can be a useful skill to have, especially for system administrators or anyone who wants to quickly reboot their server without using the graphical interface. In this blog post, we will explore different methods on how to restart Windows Server 2016 from the Command Prompt. Whether you’re looking for a quick restart or need to troubleshoot an issue, these methods will help you accomplish your goal efficiently.
Video Tutorial:
What’s Needed
To restart Windows Server 2016 from the Command Prompt, you will need:
1. Access to the Command Prompt: This can be obtained by opening the Run dialog (Win + R) and typing «cmd» or by navigating to the Command Prompt shortcut in the Start Menu.
2. Administrative Privileges: Restarting the server requires administrative privileges. Ensure that you have the necessary permissions before executing the commands.
3. Knowledge of Command Line: Familiarize yourself with basic Command Prompt commands and syntax before proceeding with these methods.
What Requires Your Focus?
When restarting Windows Server 2016 from the Command Prompt, it’s important to focus on the following aspects:
1. Required Services: Ensure that all critical services are stopped gracefully before initiating a restart. Improperly terminating services can cause data loss or system instability.
2. Active Applications: Close all active applications and save any unsaved work. Restarting the server will forcibly terminate all running processes, potentially causing data loss.
3. User Awareness: Communicate with users or clients who may be affected by the restart. Inform them about the scheduled maintenance or potential downtime to avoid any inconvenience or disruption.
Method 1. Via the “shutdown” Command
The first method to restart Windows Server 2016 from the Command Prompt is by using the «shutdown» command. This command allows you to schedule a system shutdown or restart. Follow the steps below to restart the server using this method:
1. Open the Command Prompt with administrative privileges.
2. Type the following command and press Enter:
shutdown /r
3. Windows will display a prompt informing you of the scheduled restart. If you want to proceed, press Y and then Enter.
4. The server will begin the restart process, closing all open applications and terminating running processes.
5. Wait for the server to complete the restart process. Once the server is back online, you can log in and resume your work.
Pros | Cons |
---|---|
1. Easy and straightforward way to restart the server. | 1. All running processes and applications will be terminated forcefully, potentially causing data loss if not saved. |
2. Allows you to schedule a restart for a specific time or after a certain duration. | 2. Requires administrative privileges to execute the command. |
3. Provides a grace period before initiating the restart, allowing users to save their work and close applications. | 3. Users may be unaware of the scheduled restart if not communicated properly. |
Method 2. Using the “net” Command
The second method to restart Windows Server 2016 from the Command Prompt is by using the «net» command. This command allows you to manage various network-related functions, including restarting the server. Follow the steps below to restart the server using this method:
1. Open the Command Prompt with administrative privileges.
2. Type the following command and press Enter:
net stop winmgmt
3. This command stops the Windows Management Instrumentation (WMI) service, which is responsible for system management and monitoring.
4. Type the following command and press Enter to ensure the service has stopped:
net start winmgmt
5. This command starts the WMI service again, initiating a system restart in the process.
6. The server will begin the restart process, closing all open applications and terminating running processes.
7. Wait for the server to complete the restart process. Once the server is back online, you can log in and resume your work.
Pros | Cons |
---|---|
1. Provides an alternative method to restart the server without directly using the «shutdown» command. | 1. Requires administrative privileges to execute the commands. |
2. Specifically targets the WMI service, which is responsible for system management and monitoring. | 2. All running processes and applications will be terminated forcefully, potentially causing data loss if not saved. |
3. Allows you to stop and start other services as needed, providing flexibility in managing system restarts. | 3. Users may be unaware of the scheduled restart if not communicated properly. |
Method 3. Via the Command-Line Shutdown Tool
The third method to restart Windows Server 2016 from the Command Prompt is by using the Command-Line Shutdown Tool. This tool provides additional options and flexibility compared to the standard «shutdown» command. Follow the steps below to restart the server using this method:
1. Open the Command Prompt with administrative privileges.
2. Type the following command and press Enter to see the available options:
shutdown /?
3. Review the list of available options, such as specifying a timeout period or displaying a custom message before the restart.
4. Once you have determined the desired options, type the following command and press Enter:
shutdown /r /f /t 0
5. This command initiates an immediate restart of the server (/r), forces running applications to close (/f), and sets the timeout to 0 seconds (/t 0).
6. The server will begin the restart process, closing all open applications and terminating running processes.
7. Wait for the server to complete the restart process. Once the server is back online, you can log in and resume your work.
Pros | Cons |
---|---|
1. Provides greater control over the restart process with customizable options. | 1. Requires administrative privileges to execute the command. |
2. Allows you to specify a timeout period or display a custom message before the restart. | 2. All running processes and applications will be terminated forcefully, potentially causing data loss if not saved. |
3. Offers the ability to force running applications to close, ensuring a complete restart of the server. | 3. Users may be unaware of the scheduled restart if not communicated properly. |
Method 4. Via the “wmic” Command
The fourth method to restart Windows Server 2016 from the Command Prompt is by using the «wmic» command. This command-line tool provides a wide range of options for managing various aspects of Windows systems, including restarting the server. Follow the steps below to restart the server using this method:
1. Open the Command Prompt with administrative privileges.
2. Type the following command and press Enter to access the Windows Management Instrumentation Command-line (WMIC) tool:
wmic
3. Once you are in the WMIC tool, type the following command and press Enter to restart the server:
os shutdown
4. The WMIC tool will initiate a restart of the server, closing all open applications and terminating running processes.
5. Wait for the server to complete the restart process. Once the server is back online, you can log in and resume your work.
Pros | Cons |
---|---|
1. Offers a comprehensive command-line tool for managing various aspects of Windows systems. | 1. Requires administrative privileges to execute the commands. |
2. Provides access to a wide array of options, allowing fine-tuning of restart parameters. | 2. All running processes and applications will be terminated forcefully, potentially causing data loss if not saved. |
3. Can be used to perform other system-related tasks in addition to restarting the server. | 3. Users may be unaware of the scheduled restart if not communicated properly. |
Why Can’t I Restart Windows Server 2016?
There could be several reasons why you might encounter issues when trying to restart Windows Server 2016. Here are some common reasons and their corresponding fixes:
1. Insufficient Permissions: If you don’t have administrative privileges, you won’t be able to restart the server. Ensure that you are logged in as an administrator or have the necessary permissions to execute the required commands.
2. Pending Updates: If there are pending updates that require a system restart, you may not be able to initiate a manual restart. Check for any pending updates and install them before attempting to restart the server.
3. System Services: Some critical system services may be preventing a restart. Use the Task Manager or the services management console to identify and stop any services that could be blocking the restart process.
Implications and Recommendations
When restarting Windows Server 2016 from the Command Prompt, keep the following recommendations in mind:
1. Schedule Downtime: Plan server restarts during off-peak hours to minimize disruptions to users and services.
2. Communicate with Users: Notify users in advance about scheduled server restarts to avoid any unexpected interruptions.
3. Check Application Compatibility: Ensure that critical applications and services are compatible with the server restart process. Contact vendors if necessary to confirm compatibility and any specific instructions.
5 FAQs about Restarting Windows Server 2016 from Command Prompt
Q1: Can I execute these commands remotely?
A1: Yes, you can execute commands to restart Windows Server 2016 remotely using tools like PowerShell Remoting or Windows Remote Management.
Q2: Will a server restart affect connected clients?
A2: Yes, a server restart will temporarily disrupt any connected clients or services dependent on the server. Plan accordingly and ensure appropriate communication is made to minimize any inconveniences.
Q3: Are there any risks involved in the restart process?
A3: Improper shutdown or restart procedures can potentially cause data loss or system instability. Make sure to save your work and close applications before initiating a restart.
Q4: Can I automate server restarts using these methods?
A4: Yes, you can create scripts or use task scheduling tools to automate server restarts by executing the appropriate commands at scheduled times.
Q5: Will these methods work on other versions of Windows Server?
A5: Yes, these methods should work on other versions of Windows Server, although there might be slight variations in command syntax or options. Consult the respective documentation for your specific version of Windows Server.
Final Words
Restarting a Windows Server 2016 from the Command Prompt is a valuable skill to have, especially for system administrators or anyone seeking greater control over the restart process. In this blog post, we explored different methods on how to restart Windows Server 2016 from the Command Prompt, namely via the «shutdown» command, the «net» command, the Command-Line Shutdown Tool, and the «wmic» command. We also discussed common issues that may prevent a restart and provided recommendations for a smooth restart process. By understanding these methods and following best practices, you can efficiently manage and restart your Windows Server 2016 when needed.
Windows Server in its different versions give us a range of useful options for the management and delivery of roles and services not only to the server itself but also to the client computers of the domain, hence the importance of always preserving the availability and security of this..
For administrative or support reasons, at specific times it will be necessary to shut down or restart the server for a period of time. This should only be carried out with specific orders and knowing in advance that all users are aware of this task, since otherwise we can cause failures in certain activities or prevent communication and access to shared resources.
It is well known by each of us who have or are working in Windows Server that the shutdown and restart process is usually carried out through the Start menu and by clicking on the shutdown button:
But if in TechnoWikis we tell you that this process can be done through the command line , would you do it? We already told you that managing the shutdown or restart of Windows Server can be done through commands and it is quite simple. Therefore TechnoWikis will explain some commands to perform this task and this process applies in Windows Server 2012, 2016 or 2019 equally..
To stay up to date, remember to subscribe to our YouTube channel! SUBSCRIBE
1. Shut down or restart Windows Server 2019, 2016, 2012 with Shutdown command
To use the command line, a general command called «shutdown» will be implemented, which has been integrated in all editions of Windows. Its elementary function is to turn off or restart the local or remote computer, to be taken into account, when we use this command without any parameter the device will shut down or restart immediately.
The general syntax of this command is the following:
shutdown [{-l | -s | -r | -a}] [-f] [-m [\\ device]] [-t xx] [-c "message"] [-d [u] [p] : xx: yy]
Parameters commando Shutdown
The parameters used are the following:
- -l: this parameter closes the session of the current user.
- -s: turn off the local server.
- -r: this command will be used to restart the computer after its shutdown.
- -a: it is a command with which the closing order is deleted, you can omit other parameters, minus -ly ComputerName.
- -f: this parameter forces to execute applications to proceed with the closing.
- -m [\\ ComputerName]: with this value we can indicate the equipment that has to be turned off.
- -t xx: thanks to this value we can define the timer for the shutdown of the system in xx seconds, by default its value is 20 seconds.
- -c «message»: with this parameter we can integrate a message which will be displayed in the message area of ​​the server’s shutdown window indicating that the computer has to be shut down or restarted, we can enter up to 127 characters.
- d [u] [p]: xx: yy: this is a parameter with which the code is indicated for closing, the options are u (indicates a user code), p (indicates a planned shutdown code), xx (indicates the main code (0-255)), and y (allows you to specify the secondary reason code (0-65536)).
2. Restart Windows Server 2019, 2016, 2012 with Shutdown command
Knowing the use of the shutdown command, we will see how to restart our Windows Server from the terminal.
Step 1
For an immediate restart we will execute the following. Pressing Enter will restart the system automatically.
shutdown / r / t 0
Step 2
We can enter the period of time in seconds in which the system will be restarted, for example, if we want it to restart in 1 minute we will enter the following:
shutdown / r / t 60
Step 2
The following pop-up window will automatically be displayed:
Step 3
There is indicated the time that we have defined, so, after one minute the system will be restarted:
Step 4
Now, in case of having active applications and we want to force their closing, we must execute the following:
shutdown / r / f
Step 5
In the same way, if we manage networked equipment, we can restart them remotely using the following syntax:
shutdown / r / f / m \\ EQUIPMENT
Step 6
If we want to customize the restart, we can enter a message using the -c parameter like this:
shutdown / r / t 45 -c "TechnoWikis Restart"
Step 7
As a result we will see the following:
3. Shut down Windows Server 2019, 2016, 2012 with Shutdown command
We have seen how easy it is to restart Windows Server using the command line, now, this process is similar for shutdown.
Step 1
To shut down Windows Server immediately we will execute the following:
shutdown / s / t 0
Step 2
To program the shutdown we execute:
shutdown / s / t 15
Step 3
We will see the following. There we can see a message where it says that Windows Server will close in less than a minute.
Step 4
As with the previous commands, we can force the closure of applications using:
shutdown / s / f
Step 5
To turn off a remote device we will use:
shutdown / s / f / m \\ EQUIPMENT
Step 6
Finally, to add a shutdown message we execute:
shutdown / s / t 30 -c "Shutdown TechnoWikis"
Step 7
Using one of the above commands the result will be as follows:
Thus, we already have one more solution for shutting down or restarting our Windows Server in a simple way using the shutdown command and its parameters.
Introduction
When a Windows server runs for an extended period of time, applications and operating system features can become unstable.
An unstable operating system might have application crashes, hanging applications, or memory leaks. Sometimes even essential system functions become unresponsive.
A straightforward solution is to restart. This guide will walk you through how to restart Windows Server 2016 with multiple command options.
Prerequisites
- A system running Windows Server 2016
- Command-line access
- (optional) a remote server connection
- (optional) Graphical User Interface installed
- (optional) Windows PowerShell
Using the Windows Server Restart Command
Restart Windows Server with the GUI
The Windows Server 2016 interface is a GUI, or Graphical User Interface, which simplifies many tasks.
Click the Start menu > Power button > Restart.
How to Restart Windows Server Using Command Prompt
In some cases, you may not have the GUI component installed. Or, your operating system encountered a problem, and all you can access is a command prompt.
Step 1: Open the Command Prompt
1. Press Ctrl+Alt+Del.
2. The system should present a menu – click Task Manager.
3. In the Task Manager window, click More Details.
4. Click the File menu, then click Run new task.
5. In the field, type cmd.exe– then check the box to create the task with administrator privileges. Click OK.
6. A black window with white text should appear.
Step 2: Reboot the Windows Server Operating System
In the Command Prompt window, type the Windows Server restart command, then press Enter:
shutdown –r
The –r
option tells Windows to restart, instead of simply shutting down.
Restarting from PowerShell
Windows PowerShell is like a souped-up version of the command prompt. It’s based on the .NET framework, and includes a scripting language. PowerShell is useful for tinkering under the hood of your Windows operating system.
Step 1: Launch PowerShell
1. Press Ctrl+Shift+Esc to launch the Task Manager.
2. Click the File menu, then Run new task.
3. In the prompt, type powershell.exe and tick the box to start with administrator privileges. Click OK.
4. A new window with a dark blue background should launch. You can tell you’re in a PowerShell window if the prompt begins with PS.
Step 2: Restart the System
In the PowerShell window, type the following command and press Enter:
Restart-Computer
By default, you’ll get a 5-second countdown, then the system will restart.
You can add an option to delay the restart for longer than the default 5 seconds:
Restart-Computer –delay 15
Change the number 15 to the number of seconds you wish to delay.
Rebooting a Remote Windows Server with PowerShell
Step 1: Launch PowerShell
If you are in a command prompt enter the command:
PowerShell
The prompt will add PS at the beginning, and your typed commands should appear in yellow.
Step 2: Restart Remotely
In the PowerShell window, type the following:
Restart-Computer –ComputerName “NAME_OF_SYSTEM”
Replace NAME_OF_SYSTEM with the name of the computer you want to restart. Make sure to include the quotation marks.
Note: This assumes that your current credentials are the same as those for the remote system. Typically this might look like a username of an administrator, and the same password for both systems. It can also work if both systems are on the same domain, and your user account has the appropriate permissions.
Conclusion
Restarting a Windows server is very simple, especially via the GUI.
However, even if you are having issues with the GUI or need to restart a server remotely – this guide on How to Restart Windows Server 2016 can help.
There are many different ways we can restart Windows Server 2016, in this quick guide we’ll demonstrate how to perform a reboot through the graphical user interface, with command prompt, PowerShell, or even remotely.
The command prompt and PowerShell options are particularly useful if you need to script these tasks.
Restart From GUI
If you have the graphical user interface component installed in Windows Server 2016, you can restart simply by clicking the start button followed by the Power button, and then Restart.
Restart From Command Prompt
If you do not have the GUI installed, or you simply prefer the command line, we can also perform a system reboot with the ‘shutdown’ command.
C:\> shutdown -r
The -r option is used to specify that we want to perform a reboot. By default this will start less than a minute after the command has been run, however with the use of the -t option we can alternatively specify the number of seconds we wish to wait.
Restart From PowerShell
Similarly to the above example we can perform a reboot with the command line using Microsoft’s newer PowerShell by running the ‘Restart-Computer’ cmdlet.
PS C:\> Restart-Computer
With no options specified, this will initiate a reboot of the local computer after a default period of 5 seconds. This period can be modified with the -Delay option, followed by a number of seconds to wait.
Restart Remotely
We can also use PowerShell to remotely reboot a Windows Server, again this is done with the ‘Restart-Computer’ cmdlet, except we specify the name of the computer that we want to restart.
PS C:\> Restart-Computer -ComputerName "web01"
This will initiate a restart of the ‘web01’ server, as specified by the -ComputerName option. It will only work if either the credentials on “web01” are the same as the current machine the command is run from, for instance if the remote server is a member of the same domain and your user account has these permissions.
If the remote server requires authentication, we can first use the Get-Credential cmdlet followed by the ‘computername\username’ at which point we will be prompted for the password. In the below example we store this output into the variable ‘$a’. We then perform the restart and specify the -Credential option, passing it the contents stored in $a.
Summary
We have seen that there are a number of different ways in which we can safely perform a restart of Windows Server 2016. You can perform a reboot through the GUI, command prompt, PowerShell, or even remotely from another system.