Перезагрузка из командной строки windows 2016

Когда сервер Windows работает в течение длительного периода времени, приложения и функции операционной системы могут работать нестабильно. Нестабильная операционная система может иметь сбои приложений, зависание приложений или утечки памяти. Иногда даже важные системные функции перестают отвечать.

Как перезагрузить Windows Server 2016

Простым решением является перезагрузка. В этом руководстве вы узнаете, как перезапустить Windows Server 2016 с несколькими параметрами команды.


Перезагрузить Windows Server через графический интерфейс

Интерфейс Windows Server 2016 представляет собой графический интерфейс, который упрощает многие задачи.

Нажмите: меню Пуск -> Кнопка питания -> Перезагрузить.


Как перезагрузить Windows Server с помощью командной строки

В некоторых случаях у вас может не быть установлен компонент GUI. Или ваша операционная система столкнулась с проблемой, и все, что вы можете получить доступ, это командная строка.

Шаг 1: Откройте командную строку

  1. Нажмите Ctrl + Alt + Del.
  2. Система должна показать меню — щелкните Task Manager (Диспетчер задач).
  3. В окне Task Manager (Диспетчер задач) нажмите More Details (Подробнее).
  4. Откройте меню File (Файл) и выберите Run new task (Запустить новое задание).
  5. В поле введите cmd.exe–, затем установите флажок, чтобы создать задачу с правами администратора. Нажмите ОК.
  6. Должно появиться черное окно с белым текстом.

Шаг 2. Перезагрузите операционную систему Windows Server.

В окне командной строки введите команду перезагрузки Windows Server и нажмите клавишу Enter:

shutdown –r

Параметр –r заставляет Windows перезагружаться, а не просто выключаться.


Перезапуск из PowerShell

Windows PowerShell напоминает расширенную версию командной строки. Он основан на .NET Framework и включает язык сценариев. PowerShell полезен для работы под операционной системой Windows.

Шаг 1. Запустите PowerShell

  1. Нажмите Ctrl + Alt + Del и выберите Task Manager (Диспетчер задач).
  2. Откройте меню File (Файл) и выберите Run new task (Запустить новое задание).
  3. В командной строке введите powershell.exe и установите флажок, чтобы начать с правами администратора. Нажмите ОК.
  4. Должно открыться новое окно с темно-синим фоном. Вы можете понять, что находитесь в окне 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 на имя компьютера, который вы хотите перезагрузить. Не забудьте поставить кавычки.

Примечание. Предполагается, что ваши текущие учетные данные те же, что и для удаленной системы. Обычно это может выглядеть как имя пользователя администратора, и один и тот же пароль для обеих систем. Это также может работать, если обе системы находятся в одном домене, а ваша учетная запись пользователя имеет соответствующие разрешения.

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:

image

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 

image

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:

image

Step 3

There is indicated the time that we have defined, so, after one minute the system will be restarted:

image

Step 4

Now, in case of having active applications and we want to force their closing, we must execute the following:

 shutdown / r / f 

image

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:

image

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.

image

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" 

image

Step 7

Using one of the above commands the result will be as follows:

image

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.

В 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 "комментарий"]]

команда shutdown синтаксис

Как вы видите, у команды довольно много опций, а также есть возможность выключить/ перезагрузить удаленный компьютере.

Выключение 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 минут. Сохраните свои документы!"

Пользователю будет выдано предупреждение о запланированном выключении: Ваш сеанс будет завершен.

shutdown - Ваш сеанс будет завершен.

Если задержка очень длительная, например, 100 минут (6000 секунд), то вместо предупреждающего окна появляется всплывающее сообщение в нижнем правом углу экрана: «Ваш сеанс будет завершен. Работа Windows будет завершена через 100 мин».

Отмена выключения / перезагрузки компьютера

После запуска команды выключения или перезагрузки Windows, по умолчанию утилита shutdown ожидает 60 секунд, не выполняя никаких действия. Администратор может отменить перезагрузку или выключение устройства, если в течении этого времени успеет выполнить команду:

shutdown /a

После отмены выключения появится всплывающее сообщение в нижнем правом углу экрана: «Выход из системы отменен. Запланировано завершение работы отменено».

shutdown /a - отмена перезагрузки Выход из системы отменен

Перезагрузить Windows немедленно

Чтобы выключить или перезагрузить компьютер немедленно, не ожидая стандартные 60 секунд, нужно указать значение 0 для параметра /t. Например, для немедленной перезагрузки компьютера:

shutdown /r /t 0

Очень важный ключ /f. Я использую его практически всегда при выключении или перезагрузки серверов Windows. Данный атрибут обеспечивает принудительное завершение всех запущенных программ и процессов, не ожидая подтверждения от пользователя (не будем же мы ждать подтверждения закрытия программ от всех пользователей на терминальном сервере, его можно просто не дождаться).

Следующая команда выполнит перезагрузку компьютера с автоматическим запуском всех зарегистрированных приложений после перезагрузки (имеются в виду приложения, зарегистрированные в системе с использованием функции API RegisterApplicationRestart).

shutdown /g

Ярлык для перезагрузки компьютера

Для удобства пользователей вы можете создать на рабочем столе ярлыки для выключения или перезагрузки компьютера с нужными настройками. Такой ярлык может быть полезен для выполнения перезагрузки из RDP сессии, когда отсутствуют кнопки перезагрузки/завершения работы компьютера в меню Пуск.

ярлык на рабочем столе для перезагрузки компьютера

Перезагрузка Windows в определенное время

Чтобы всегда перезагружать/выключать компьютер или сервер в определенное время, вы можете добавить команду shutdown в планировщик заданий Windows taskschd.msc.

Например, следующее задание планировщика будет ежедневно перезагружать компьютер ночью в 0:00.

задание планировщика для ежедневной перезагрузки компьютера командой shutdown

Либо вы можете создать новое задание планировщика из 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 /r //m - перезагрузка удаленного компьютера

Если все указанные условия выполняются, но при выполнении команды 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

shutdown /i - графический интерфейс команды shutdown

Как вы видите, в диалоге удаленного завершения работы вы можете добавить несколько компьютеров, которые нужно перезагрузить/выключить, указать текст уведомления и задать причину выключения для сохранения в журнале Windows.

Перезагрузка и выключение Windows с помощью PowerShell

В PowerShell есть две команды для выключения и перезагрузки компьютера: Restart-Computer и Stop-Computer. Обе команды позволяют выключить или перезагрузить локальный или удаленный компьютер по сети.

powershell команда Restart-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).

restart-computer ошибка при удаленной перезагрузке компьютера по сети 0x80070005

Если на удаленном компьютере настроен 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.

Restart-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.

Удаленная перезагрузка компьютера из powershell

Можно дождаться запуска службы удаленного рабочего стола (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


Posted by
on September 15, 2016

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.

PowerShell Get-Credential

PowerShell Restart-Computer Remotely

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.

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:

  1. Open PowerShell: Search for it in the start menu or type powershell in the Run dialog.
  2. Restart-Computer Command: Use the command Restart-Computer. This straightforward command initiates an immediate restart of the server.
    
    Restart-Computer
    
    
  3. Adding Parameters: Similar to Command Prompt, you can add parameters like -Delay to set a timer for the restart.
    
    Restart-Computer -Delay 60
    
    
  4. 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.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Rpc error windows server
  • Dazzle dvc100 driver windows 7
  • Как экспортировать контакты из windows live в outlook
  • Как сменить рабочий стол в windows 11 комбинация клавиш
  • Roland sound canvas windows