Powershell перезагрузка удаленного компьютера

Обновлено: 07.07.2024

Системному администратору неизбежно потребуется перезапустить сервер или систему. Вместо того, чтобы проходить через пользовательский интерфейс, PowerShell предоставляет несколько методов для удаленной перезагрузки компьютера.

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

Возможно, вы знакомы с командлетом Restart-Computer, но знаете ли вы, что есть еще много других способов?

Содержание

  • Что нам понадобиться
  • Перезагрузка удаленного компьютера с помощью Restart-Computer
  • Перезагрузка удаленного компьютера с помощью Invoke-CimMethod
  • Использование shutdown.exe для удаленной перезагрузки компьютера
  • Перезагрузка компьютера удаленно с помощью PSExec.exe
  • Параллельный перезапуск нескольких систем
  • Вывод

Что нам понадобиться

Перезагрузка удаленного компьютера с помощью командлета Restart-Computer

Как вы можете видеть в приведенном ниже примере, это, как правило, наиболее простой метод и подходящее решение для большинства сценариев PowerShell.

Перезагрузка удаленного компьютера помощью Invoke-CimMethod

Не предназначен специально для удаленной перезагрузки системы.
Invoke-CimMethod работает с использованием метода WIM для перезагрузки удаленной системы.
Не такой гибкий, как Restart-Computer командлет, но вы можете удаленно перезагрузить систему с помощью собственной команды PowerShell.

Использование shutdown.exe для удаленной перезагрузки компьютера

Удаленная перезагрузка компьютера с помощью PSExec.exe

Параллельный перезапуск нескольких систем

Большинству системных администраторов в тот или иной момент потребуется перезапустить несколько систем. Есть несколько способов сделать это с помощью определенных команд.
Параллельный перезапуск нескольких компьютеров легко выполняется с помощью PowerShell 7 и команды Restart-Computer .

Вывод

Использование PowerShell для перезагрузки компьютеров в сети является важным и полезным умением системного администратора Windows. Поскольку PowerShell обладает уникальной способностью запускать сторонние команды из скриптов и функций, вы сможете использовать PowerShell для «склеивания» различных методов вместе в зависимости от ваших потребностей!

Перезагрузка удаленного компьютера через Powershell

В Powershell есть возможность удаленного выполнения команд. Этот механизм я описывал в этой статье. Если вы никогда не исполняли командлеты типа Invoke-Command или New-PSSession я попробую вкратце объяснить.

Вообще для удаленной перезагрузки Powershell нужно выполнить следующий командлет:

Где:
$cred - переменная, которая хранит учетные данные (логин/пароль). Она не обязательна, если вы администратор на удаленном компьютере
-ComputerName - имя компьютера, который будем перезагружать
-ScriptBlock - значит, что мы посылаем команду перезагрузки

Второй вариант такой:

Отличия между командами в том, что в первом случае мы посылаем команду перезагрузки сразу, а во втором мы сначала подключаемся, а затем перезагружаем компьютер через Powershell. Отмечу, что во втором случае, если команда не выполнится то вы можете перезагрузить свой компьютер (выполняйте последовательно что бы предотвратить это).

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

Если вы находитесь в домене, то удаленные команды Powershell должны выполнится при условии, что у вас запущен WinRM, а он запускается так:

Вы так же должны быть с полномочиями администратора удаленного компьютера (по умолчанию WinRM работает так). Если вместо имени компьютера вы используете IP или вы не в домене, то вы используете не Kerberos, а NTLM и он по умолчанию выключен. Для этого вам нужно либо выпустить SSL сертификат, либо должны выполнить такую команду:

Где вместо 192.168.3.134 должны вписать IP компьютера к которому хотите подключиться. Можно сделать и так:

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

Если у вас все же не получается перезагрузить компьютер, попробуйте прочитать эту статью.

Restarts the operating system on local and remote computers.

Syntax

Description

This cmdlet is only available on the Windows platform.

The Restart-Computer cmdlet restarts the operating system on the local and remote computers.

You can use the parameters of Restart-Computer to run the restart operations, to specify the authentication levels and alternate credentials, to limit the operations that run at the same time, and to force an immediate restart.

Starting in Windows PowerShell 3.0, you can wait for the restart to complete before you run the next command. Specify a waiting time-out and query interval, and wait for particular services to be available on the restarted computer. This feature makes it practical to use Restart-Computer in scripts and functions.

Examples

Example 1: Restart the local computer

Restart-Computer restarts the local computer.

Example 2: Restart multiple computers

Restart-Computer can restart remote and local computers. The ComputerName parameter accepts an array of computer names.

Example 3: Get computer names from a text file

Restart-Computer gets a list of computer names from a text file and restarts the computers. The ComputerName parameter isn't specified. But because it's the first position parameter, it accepts the computer names from the text file that are sent down the pipeline.

Get-Content uses the Path parameter to get a list of computer names from a text file, Domain01.txt. The computer names are sent down the pipeline. Restart-Computer restarts each computer.

Example 4: Force restart of computers listed in a text file

This example forces an immediate restart of the computers listed in the Domain01.txt file. The computer names from the text file are stored in a variable. The Force parameter forces an immediate restart.

Get-Content uses the Path parameter to get a list of computer names from a text file, Domain01.txt. The computer names are stored in the variable $Names . Get-Credential prompts you for a username and password and stores the values in the variable $Creds . Restart-Computer uses the ComputerName and Credential parameters with their variables. The Force parameter causes an immediate restart of each computer.

Example 6: Restart a remote computer and wait for PowerShell

Restart-Computer restarts the remote computer and then waits up to 5 minutes (300 seconds) for PowerShell to become available on the restarted computer before it continues.

Restart-Computer uses the ComputerName parameter to specify Server01. The Wait parameter waits for the restart to finish. The For specifies that PowerShell can run commands on the remote computer. The Timeout parameter specifies a five-minute wait. The Delay parameter queries the remote computer every two seconds to determine whether it's restarted.

Example 7: Restart a computer by using WsmanAuthentication

Restart-Computer restarts the remote computer using the WsmanAuthentication mechanism. Kerberos authentication determines whether the current user has permission to restart the remote computer. For more information, see AuthenticationMechanism.

Restart-Computer uses the ComputerName parameter to specify the remote computer, Server01. The WsmanAuthentication parameter specifies the authentication method as Kerberos.

Parameters

Specifies one computer name or a comma-separated array of computer names. Restart-Computer accepts ComputerName objects from the pipeline or variables.

Type the NetBIOS name, an IP address, or a fully qualified domain name of a remote computer. To specify the local computer, type the computer name, a dot . , or localhost.

This parameter doesn't rely on PowerShell remoting. You can use the ComputerName parameter even if your computer isn't configured to run remote commands.

If the ComputerName parameter isn't specified, Restart-Computer restarts the local computer.

Type:String [ ]
Aliases:CN, __SERVER, Server, IPAddress
Position:0
Default value:None
Accept pipeline input:True
Accept wildcard characters:False

Prompts you for confirmation before running Restart-Computer .

Type:SwitchParameter
Aliases:cf
Position:Named
Default value:False
Accept pipeline input:False
Accept wildcard characters:False

Specifies a user account that has permission to do this action. The default is the current user.

Type a user name, such as User01 or Domain01\User01, or enter a PSCredential object generated by the Get-Credential cmdlet. If you type a user name, you're prompted to enter the password.

Credentials are stored in a PSCredential object and the password is stored as a SecureString.

For more information about SecureString data protection, see How secure is SecureString?.

Type:PSCredential
Position:1
Default value:Current user
Accept pipeline input:False
Accept wildcard characters:False

Specifies the frequency of queries, in seconds. PowerShell queries the service specified by the For parameter to determine whether the service is available after the computer is restarted.

This parameter is valid only together with the Wait and For parameters.

This parameter was introduced in Windows PowerShell 3.0.

If the Delay parameter isn't specified, Restart-Computer uses a five second delay.

Type:Int16
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

Specifies the behavior of PowerShell as it waits for the specified service or feature to become available after the computer restarts. This parameter is only valid with the Wait parameter.

  • Default: Waits for PowerShell to restart.
  • PowerShell: Can run commands in a PowerShell remote session on the computer.
  • WMI: Receives a reply to a Win32_ComputerSystem query for the computer.
  • WinRM: Can establish a remote session to the computer by using WS-Management.

This parameter was introduced in Windows PowerShell 3.0.

Type:WaitForServiceTypes
Accepted values:Wmi, WinRM, PowerShell
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

Forces an immediate restart of the computer.

Type:SwitchParameter
Aliases:f
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

Specifies the duration of the wait, in seconds. When the timeout elapses, Restart-Computer returns to the command prompt, even if the computers aren't restarted.

The Timeout parameter is only valid with the Wait parameter. Timeout overrides the Wait parameter's indefinite waiting period.

This parameter was introduced in Windows PowerShell 3.0.

Type:Int32
Aliases:TimeoutSec
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

Restart-Computer suppresses the PowerShell prompt and blocks the pipeline until the computers have restarted. You can use this parameter in a script to restart computers and then continue to process when the restart is finished.

The Wait parameter waits indefinitely for the computers to restart. You can use Timeout to adjust the timing and the For and Delay parameters to wait for particular services to become available on the restarted computers.

The Wait parameter isn't valid when you're restarting the local computer. If the value of the ComputerName parameter contains the names of remote computers and the local computer, Restart-Computer generates a non-terminating error for Wait on the local computer, but waits for the remote computers to restart.

This parameter was introduced in Windows PowerShell 3.0.

Type:SwitchParameter
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

Shows what would happen if the Restart-Computer runs. The Restart-Computer cmdlet isn't run.

Type:SwitchParameter
Aliases:wi
Position:Named
Default value:False
Accept pipeline input:False
Accept wildcard characters:False

Specifies the mechanism that is used to authenticate the user credentials. This parameter was introduced in Windows PowerShell 3.0.

Credential Security Service Provider (CredSSP) authentication, in which the user credentials are passed to a remote computer to be authenticated, is designed for commands that require authentication on more than one resource, such as accessing a remote network share. This mechanism increases the security risk of the remote operation. If the remote computer is compromised, the credentials that are passed to it can be used to control the network session.

Как использовать PowerShell для перезагрузки удаленного компьютера

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

Предварительным условием использования этих методов является обеспечение возможности связи с удаленными системами и аутентификации при необходимости. Кроме того, вам необходимо убедиться, что удаленная система не ожидает перезагрузки.

Вам понадобится следующее:

1]Перезагрузите удаленный компьютер с помощью Restart-Computer

Этот командлет прост в использовании с гибкими параметрами. Дополнительным условием для работы команды является то, что WinRM настроен и разрешен через брандмауэр Windows удаленного компьютера, а WMI разрешен через брандмауэр Windows.

Чтобы перезагрузить несколько компьютеров параллельно, выполните следующую команду:

2]Перезагрузите удаленный компьютер с помощью Invoke-CimMethod

В Invoke-CimMethod работает с использованием метода WIM для перезагрузки удаленной системы, хотя и не так гибко, как Restart-Computer командлет.

Дополнительным предварительным условием для работы команды является то, что WinRM настроен и разрешен через брандмауэр Windows удаленного компьютера.

3]Перезагрузите удаленный компьютер с помощью shutdown.exe.

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

4]Перезагрузите удаленный компьютер с помощью PSExec.exe.

Одна из наиболее часто используемых утилит в наборе инструментов Sysinternals, psexec.exe предлагает несколько уникальных возможностей, которые упрощают взаимодействие с удаленной системой.

Дополнительным предварительным условием для работы команды является обеспечение работы службы SMB, включения общего доступа к файлам и принтерам, отключения простого общего доступа к файлам и доступности административного общего ресурса admin $.

5]Перезагрузите удаленный компьютер с помощью RunDLL32.exe.

В rundll32.exe предлагает способ запуска определенных методов для внутренних исполняемых файлов и API-интерфейсов Windows, таких как shell32.dll. Есть два метода, с помощью которых вы можете перезапустить систему, используя эту функцию, но на самом деле этот метод нельзя использовать удаленно сам по себе. Invoke-Command в удаленной системе.

Способ 1:

Способ 2:

6]Перезагрузите удаленный компьютер с помощью Taskkill.exe.

Вот и все, о 6 способах использования PowerShell для перезагрузки удаленного компьютера!

Читайте также: