Как выключить сервер через консоль windows

В 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

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.

We continue to explore the features of Windows Server 2022. It is well known that this is Microsoft’s next solution for enterprise environments. Well, like its predecessors, this version has variants with and without a graphical environment. In addition, it is well known that a common task is to shut down or restart the server. Therefore, this can be done from the start menu. However, in environments without a graphical plug-in, then we can do it from the command line. Read on to find out How to shutdown and reboot Windows Server 2022 with commands.

How to restart Windows Server 2022

The first thing you have to do is to open a CMD as administrator. Then use the following syntax:

shutdown /r /t time

Please replace Time with the time you want to wait for the server to restart.

Scheduling Windows Server 2022 reboot

Scheduling Windows Server 2022 reboot

This means that after 200 seconds, the server will be restarted. On the other hand, it is possible to add a message at restart time. For this purpose, just add the -c parameter:

shutdown /r /t time -c  message

The server will restart after the timeout period has elapsed. On the other hand, sometimes there are open programs that prevent a restart. In such a case it is possible to force a shutdown using the following command:

shutdown /r /f

It is even possible to schedule this task for a remote computer. With this in mind, use the following syntax:

shutdown /r /f /m \\Computer

How to shutdown Windows Server 2022 with commands

The commands for shutting down the server are very similar to that for restarting it. In fact, only the first element changes. So use the following syntax:

shutdown /s /t time
Scheduling server shutdown after 400 seconds

Scheduling server shutdown after 400 seconds

To add a message we use the -c parameter as follows:

shutdown /s /t time -c message

To force applications to close we run:

shutdown /s /f

It is also possible to use it with remote computers:

shutdown /s /f /m \\COMPUTER

Ultimately, we have seen how to shutdown and reboot Windows Server 2022 with commands. Consequently, we have an expeditious way to manage these tasks on the server. Bye!

— Advertisement —

Everything Linux, A.I, IT News, DataOps, Open Source and more delivered right to you.

Subscribe

«The best Linux newsletter on the web»

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Appearance settings

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.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Улучшение шрифта windows 10
  • Драйвер для видеокарты nvidia geforce gtx 750 ti для windows 10 64 bit
  • Код доступа windows 10 pro
  • Как сделать откат системы windows 10 через биос на компьютере
  • Bass booster для windows