- Как перезагрузить компьютер удаленно через Powershell
- В чем могут быть проблемы при удаленной перезагрузки компьютера
- Restart computer windows powershell
- Удаленная перезагрузка компьютера
- Перезагрузка компьютера с задержкой по времени
- Скрипт PowerShell для перезагрузки по расписанию
- Adam the Automator
- How to Use PowerShell to Restart Computers (All the Ways!)
- Adam Listek
- Prerequisites
- Restarting a Computer with Restart-Computer
- Restarting a Computer with PowerShell and Invoke-CimMethod
- Running shutdown.exe to Remotely Restart a Computer
- Restarting Computers with PSExec.exe
- Bonus Methods!
- RunDLL32.exe
- Taskkill.exe
- Restarting Multiple Systems in Parallel
Как перезагрузить компьютер удаленно через Powershell
В Powershell есть возможность удаленного выполнения команд. Этот механизм я описывал в этой статье. Если вы никогда не исполняли командлеты типа Invoke-Command или New-PSSession я попробую вкратце объяснить.
Вообще для удаленной перезагрузки Powershell нужно выполнить следующий командлет:
Где:
$cred — переменная, которая хранит учетные данные (логин/пароль). Она не обязательна, если вы администратор на удаленном компьютере
-ComputerName — имя компьютера, который будем перезагружать
-ScriptBlock
Второй вариант такой:
Отличия между командами в том, что в первом случае мы посылаем команду перезагрузки сразу, а во втором мы сначала подключаемся, а затем перезагружаем компьютер через Powershell. Отмечу, что во втором случае, если команда не выполнится то вы можете перезагрузить свой компьютер (выполняйте последовательно что бы предотвратить это).
В чем могут быть проблемы при удаленной перезагрузки компьютера
Если вы находитесь в домене, то удаленные команды Powershell должны выполнится при условии, что у вас запущен WinRM, а он запускается так:
Вы так же должны быть с полномочиями администратора удаленного компьютера (по умолчанию WinRM работает так). Если вместо имени компьютера вы используете IP или вы не в домене, то вы используете не Kerberos, а NTLM и он по умолчанию выключен. Для этого вам нужно либо выпустить SSL сертификат, либо должны выполнить такую команду:
Где вместо 192.168.3.134 должны вписать IP компьютера к которому хотите подключиться. Можно сделать и так:
Но в этом случае вы сможете подключаться ко всем компьютерам. Проблема в том, что NTLM не осуществляет проверку подлинности и из-за этого такой вариант не рекомендуется.
Если у вас все же не получается перезагрузить компьютер, попробуйте прочитать эту статью.
Restart computer windows powershell
Добрый день! Уважаемые читатели и гости одного из крупнейших IT блогов рунета Pyatilistnik.org. В прошлый раз мы с вами разбирали перезагрузку сервера из командной строки, в данной публикации я хочу вас научить обычной и удаленной перезагрузке компьютера средствами PowerShell, который прочно вошел в нашу жизнь. Уверен, что вы сами сможете определить себе сценарии, которые сможете использовать в своей практике.
Перезагрузка компьютера, это базовая процедура в операционной системе, и для большинства людей достаточно графического варианта, но бывают ситуации, что у вас может быть с помощью групповой политики убрана кнопка перезагрузки, или же вам нужно перезагрузить сразу пачку серверов, в таких ситуациях вас выручит PowerShell.
Открываем окно PowerShell в режиме администратора и знакомимся с командлетом Restart-Computer.Первое, что я вам советую сделать, это ознакомиться со справкой командлета, для этого введите:Для того, чтобы была выполнена локальная перезагрузка компьютера, вам достаточно ввести данный командлет:
Как видим компьютер уходит в перезагрузку.
Так же можно использовать команду с добавлением ключа -ComputerName
Тут так же будет выполнена перезагрузка компьютера, хочу отметить, что localhost означает локальный компьютер, но вам никто не мешает тут ввести и имя локального компьютера.
Удаленная перезагрузка компьютера
Как я и говорил ранее PowerShell, это прекрасный инструмент по удаленному управлению компьютерами, серверами и службами. Предположим, что у меня есть RDS ферма состоящая из 10 серверов с Windows Server 2019. Мне необходимо произвести обслуживание четырех серверов, для этого я перевожу их в режим стока (Drain Mode) чтобы отсечь новые подключения, и рассылаю уведомление сотрудникам, через msg, чтобы сотрудники перелогинились. После я начинаю обслуживать данные системы, когда я заканчиваю, то мне необходимо их перезагрузить. Для этого мы воспользуемся вот такой конструкцией:
После выполнения команды компьютер уходит в перезагрузку, если этого не произошло, то вы с большой вероятностью получите ошибку:
+ CategoryInfo : OperationStopped: (w10-cl02:String) [Restart-Computer], InvalidOperationException
+ FullyQualifiedErrorId : RestartcomputerFailed,Microsoft.PowerShell.Commands.RestartComputerCommand
Restart-Computer : Не удалось перезагрузить компьютер w10-cl03 со следующим сообщение об ошибке: Невозможно инициировать завершение работы системы, так как компьютер используется другими пользователями.
строка:1 знак:1
+ Restart-Computer -ComputerName w10-cl02, w10-cl03
+
+ CategoryInfo : OperationStopped: (w10-cl03:String) [Restart-Computer], InvalidOperationException
+ FullyQualifiedErrorId : RestartcomputerFailed,Microsoft.PowerShell.Commands.RestartComputerCommand
Тут вся загвоздка в том, что за компьютерами остались активные сессии работающих пользователей, именно в интерактивном режиме. В таких случаях, если они не вышли и не реагируют на ваши сообщения, вы можете принудительно произвести перезагрузку компьютера с чистой совестью. Для этого можно использовать ключ -Force, в результате PowerShell конструкцию будет выглядеть таким образом:
Как видим команда успешно отработала и была произведена перезагрузка компьютера.
Если вы хотите перезагрузить удаленный компьютер от имени определенного пользователя, то данный командлет вам это позволит сделать. Для этого введите:
В результате у вас появится окно для ввода пароля пользователя, указываем его и нажимаем «Ok». Кстати если на удаленном компьютере, который требуется перезагрузить, будет активная сессия пользователя в интерактивном режиме, то вам так же выскочит ошибка, что «компьютер используется другими пользователями» и вам нужно будет добавлять ключик -Force:
В логах Windows на тех компьютерах, в журнале система, вы сможете обнаружить событие с кодом ID 1074(/kak-uznat-kto-perezagruzil-server-windows/), в котором вы увидите, кто перезагрузил систему:
Предположим, что у вас есть список компьютеров, которые требуется удаленно перезагрузить. В такой ситуации сам Бог велел использовать PowerShell. Структура файла выглядит очень просто, обычный текстовый документ, формата txt. На каждой строке по одному имени компьютера, без запятых. Я положил его в корень диска C:\.
Для того, чтобы прочитать данный файл есть командлет Get-Content и конструкция команды принимает вот такой вид:
В итоге удаленная перезагрузка компьютера через PowerShell успешно отработала и все системы из файла обслужены.
Перезагрузка компьютера с задержкой по времени
Еще очень частая ситуация, это перезапуск компьютера, но через определенное время, предположим, через 60 секунд, чтобы какие-то другие вещи успели отработать, очень часто применяется в сценариях и скриптах. Для выполнения это задачи есть командлет Start-Sleep. Пишем команду:
В ключе -Seconds вы задаете время в секундах.
так же у вас есть возможность определить механизм, который используется для аутентификации учетных данных пользователя. Этот параметр был введен в Windows PowerShell 3.0. Называется этот ключ -WsmanAuthentication. На выбор у вас будет пять вариантов: Basic, CredSSP, Default, Digest, Kerberos и Negotiate.
В моем примере я буду использовать проверку подлинности Kerberos, напоминаю, что для этого у вас на удаленных компьютерах должна быть настроена служба WinRM и политика, определяющая с каких ip-адресов вы можете производить подключение к ней. В итоге команда принимает такой вид:
После ее выполнения удаленные компьютеры уходят в перезагрузку.
Скрипт PowerShell для перезагрузки по расписанию
Предположим, что вам нужно перезагрузить компьютер по расписанию, это можно сделать и групповыми политиками, а так же и через задачу по расписанию, актуально для компьютеров не в домене. Вы в задаче подкладывает ваш скрипт PowerShell, чтобы выполнять его в нужное время, но с уведомлением человека. Ниже текст скрипта.
$wshell.Popup(«Данный компьютер будет перезагружен»,10,»Сохраните свои данные»,0x0)
$wshell.Popup(«Перезагрузка будет через 30 секунд»,2,»Не забудьте сохранить данные»,0x0)
Restart-Computer -ComputerName w10-cl01
Еще бонусом перезагрузка локального компьютера может быть выполнена и с помощью WMI. Для этого в оболочке PowerShell введите;
Adam the Automator
How to Use PowerShell to Restart Computers (All the Ways!)
Adam Listek
Read more posts by this author.
Inevitably a system administrator will need to restart a server or system. Rather than stepping through the user interface, why not use PowerShell to restart the computer (or lots of computers!)?
In this article, you’re going to learn all the ways to manage computer restarts with PowerShell. We’re going a lot deeper than just using the Restart-Computer cmdlet.
Table of Contents
Prerequisites
This tutorial is going to be a guide taking you through various methods to use PowerShell to restart computers. If you intend to follow along, be sure you have the following:
- A user account on any computer (local or remote) in the local Adminstrators group
- Windows PowerShell or PowerShell Core. The tutorial will use Windows PowerShell 5.1.
- WinRM is configured and allowed through the remote computer’s Windows firewall and that WMI is allowed through the Windows firewall
Restarting a Computer with Restart-Computer
The first PowerShell specific method, and most common, is the PowerShell Restart-Computer cmdlet. This cmdlet is simple to use with flexible parameters, some of which make script integration very easy.
As you can see in the example below, this is generally the most straightforward method and go-to solution for most PowerShell scripts.
The simple example below connects to a remote computer called SRV1. To skip the default confirmation, it uses the Force parameter to restart the computer.
The Restart-Computer cmdlet has a few parameters to configure how to command interacts with the computer as shown below.
- ComputerName – The system that you intend to restart. This parameter can take the following remote addresses, NetBIOS, IP Address, or the Fully Qualified Domain Name (FQDN). For the local system use . , localhost , or omit the parameter.
- Force – Used if other users are currently on the system. This will force a shutdown.
- Wait – This parameter will block the prompt and pipeline indefinitely (unless paired with the timeout parameter). This works in conjunction with the For parameter to poll for a specific component to become available.
- Timeout – Used with the Wait parameter, this will ensure that the restart doesn’t block the prompt and pipeline indefinitely if there is a problem.
- For – There are a few components that PowerShell can look for to indicate a successful restart. By default, Restart-Computer looks to see if PowerShell itself is running to indicate a successful restart operation. Another option is to wait for WMI or WinRM to be available.
- Delay – By default, the cmdlet will poll every 5 seconds for the defined component to check while waiting for a remote system to become available. This parameter will override that default delay time period.
The ComputerName parameter does not use WinRM for the remote system call, therefore, you don’t need to worry about if the local system is configured for WinRM.
Restarting a Computer with PowerShell and Invoke-CimMethod
Not specifically intended for rebooting a system remotely, Invoke-CimMethod works by using a WIM method to reboot the remote system. Not as flexible as the Restart-Computer cmdlet, you can remotely reboot a system using a native PowerShell command.
Ensure that WinRM is configured and allowed through the remote computer’s Windows firewall for this method.
The Invoke-CimMethod has a few parameters you should be aware of.
- ClassName – The name of CIM class to use. In the case of a restart command, we are using the Win32_OperatingSystem class.
- ComputerName – Using the WsMan protocol, you can use any of the following remote address types, NetBIOS, IP Address, or the Fully Qualified Domain Name (FQDN). If this parameter is omitted, then local operations are performed using COM.
- MethodName – The method name is the WMI method for the class that is being targeted. In the case of a restart operation, you will need to use the Reboot method.
Running shutdown.exe to Remotely Restart a Computer
Moving on from PowerShell-specific cmdlets, we come to the standard built-in executable that Windows offers to restart a system. The shutdown.exe executable has been around a long time and offers a robust series of options.
Although not technically a PowerShell cmdlet, you can still use PowerShell to restart computers with shutdown.exe by invoking as an executable.
Below are the parameters for the shutdown command you should know.
- r – Restarts a computer after first shutting the system down.
- g – This is similar to the r command, but will also restart any registered applications upon startup. Introduced in Windows Vista, the Windows Restart Manager allows gracefully shutting down and restarting applications registered with this system. An example would be the Outlook application which is automatically started back up, if it was open initially upon shutdown.
- e – Document the reason for an unexpected restart of the system.
- m – The remote system to restart, takes the parameter of \\computername .
- t – The time in seconds before initiating the restart operation. If a value greater than 0 is defined, the f (force) parameter is implied. The default value is 30 seconds, but no force.
- c – An optional restart message that will appear on-screen before the shutdown and also in the Windows event log comment and can be up to 512 characters.
- f – Force any running applications to close, which will not prompt for a File→Save prompt in any application and may cause data loss.
- d – Listing of a reason code for the restart operation. An example of this type of reason code is P:2:18 which corresponds to Operating System: Security fix (Planned).
Restarting Computers with PSExec.exe
One of the most used utilities within the Sysinternals toolkit, psexec.exe offers several unique abilities that make interacting with a remote system easy. Taking a different approach than both PowerShell and built-in utilities, psexec.exe creates a service on the remote system that commands are then proxied through.
Ensure the SMB Service is running, file and printer sharing is enabled, simple file sharing is disabled and the admin$ administrative share is available for this method.
- d – Use psexec non-interactively by not waiting for the process to terminate, useful in scripts.
- h – If the target system is Vista or higher, run this process using the account’s elevated token, if available.
- n – Specifies a timeout in seconds while connecting to a remote computer.
- s – Run the process using the system account, which confers a much higher level of access than the typical administrative account. This is not always needed, or used, but a very useful ability to have.
- computer – A positional parameter that takes the form of \\remotecomputer this allows usage of psexec against a remote system.
- cmd – Another positional parameter that is used to specify the actual command to run against the system. Since psexec does not do the rebooting of the system itself, this command will be another utility such as shutdown.exe used to restart a system.
- arguments – This positional parameter contains any arguments that are needed to be passed to the previously defined cmd .
- accepteula – If psexec has not recorded that you have accepted the EULA, the tool would typically show an on-screen prompt to accept the EULA. This will accept that EULA without the graphical prompt.
- nobanner – When connecting to a remote system, there is banner information displayed from the tool, which nobanner will suppress.
Bonus Methods!
The methods shown below are not very commonly used but could be useful depending on the needs.
RunDLL32.exe
The rundll32.exe offers a way to run certain methods against internal executables and Windows APIs, such as shell32.dll. There are two methods you can restart a system using this functionality.
- rundll32.exe user.exe ExitWindowsExec – Restarts the local system.
- rundll32.exe shell32.dll,SHExitWindowsEx 2 – Will also restart the local system.
This method cannot be actually used remotely by itself, but you can combine this with PowerShell via an Invoke-Command on a remote system.
Taskkill.exe
Finally, taskkill.exe is one other Windows utility that offers some functionality to restart computers, though in a roundabout way. By ending the lsass.exe process, you will force a Windows restart.
Restarting Multiple Systems in Parallel
Most system administrators will need to restart multiple systems at one point or another. Let’s take a quick look at how one might be able to tie these commands together to do this.
Restarting multiple computers with PowerShell in parallel is easy using PowerShell 7 and the Restart-Computer command.
As you can tell with the newer ForEach-Object -Parallel ability, it’s trivial to add parallelization onto your commands. Since Restart-Computer supports remote restarting natively when combined with ForEach-Object the ease of managing and restarting large systems can quickly be done!