Execute windows command from powershell

Выполнение удаленных команд Running Remote Commands

Одна команда Windows PowerShell позволяет запускать команды на одном или сотнях компьютеров. You can run commands on one or hundreds of computers with a single PowerShell command. Windows PowerShell поддерживает удаленное вычисление с помощью разных технологий, включая WMI, RPC и WS-Management. Windows PowerShell supports remote computing by using various technologies, including WMI, RPC, and WS-Management.

PowerShell Core поддерживает инструментарий WMI, WS-Management и удаленное взаимодействие через SSH. PowerShell Core supports WMI, WS-Management, and SSH remoting. В PowerShell 6 RPC больше не поддерживается. In PowerShell 6, RPC is no longer supported. В PowerShell 7 и более поздних версиях RPC поддерживается только в Windows. In PowerShell 7 and above, RPC is supported only in Windows.

Дополнительные сведения об удаленном взаимодействии в PowerShell Core см. в следующих статьях: For more information about remoting in PowerShell Core, see the following articles:

Удаленное взаимодействие с Windows PowerShell без настройки Windows PowerShell Remoting Without Configuration

Многие командлеты Windows PowerShell имеют параметр ComputerName, который позволяет собирать данные и изменять параметры одного или нескольких удаленных компьютеров. Many Windows PowerShell cmdlets have the ComputerName parameter that enables you to collect data and change settings on one or more remote computers. Эти командлеты используют разные протоколы связи и работают во всех операционных системах Windows без специальной настройки. These cmdlets use varying communication protocols and work on all Windows operating systems without any special configuration.

В эти командлеты входят следующие: These cmdlets include:

Обычно командлеты, которые поддерживают удаленное взаимодействие без специальной настройки, имеют параметр ComputerName, но не имеют параметра Session. Typically, cmdlets that support remoting without special configuration have the ComputerName parameter and don’t have the Session parameter. Чтобы найти эти командлеты в сеансе, введите: To find these cmdlets in your session, type:

Служба удаленного взаимодействия Windows PowerShell Windows PowerShell Remoting

Благодаря использованию протокола WS-Management служба удаленного взаимодействия Windows PowerShell позволяет запустить любую команду Windows PowerShell на одном или нескольких удаленных компьютерах. Using the WS-Management protocol, Windows PowerShell remoting lets you run any Windows PowerShell command on one or more remote computers. Вы можете устанавливать постоянные подключения, запускать интерактивные сеансы и выполнять скрипты на удаленных компьютерах. You can establish persistent connections, start interactive sessions, and run scripts on remote computers.

Чтобы использовать службу удаленного взаимодействия Windows PowerShell, удаленный компьютер должен быть настроен для удаленного управления. To use Windows PowerShell remoting, the remote computer must be configured for remote management. Дополнительные сведения, в том числе инструкции, см. в разделе about_Remote_Requirements. For more information, including instructions, see About Remote Requirements.

После настройки службы удаленного взаимодействия Windows PowerShell вы получите доступ ко многим стратегиям удаленного взаимодействия. Once you have configured Windows PowerShell remoting, many remoting strategies are available to you. В этой статье перечислены только некоторые из них. This article lists just a few of them. См. дополнительные сведения об удаленном взаимодействии. For more information, see About Remote.

Читайте также:  Comctl32 ocx windows 10 x64

Запуск интерактивного сеанса Start an Interactive Session

Чтобы запустить интерактивный сеанс с одним удаленным компьютером, используйте командлет Enter-PSSession. To start an interactive session with a single remote computer, use the Enter-PSSession cmdlet. Например, чтобы запустить интерактивный сеанс с удаленным компьютером Server01, введите: For example, to start an interactive session with the Server01 remote computer, type:

В командной строке отобразится имя удаленного компьютера. The command prompt changes to display the name of the remote computer. Все команды, введенные в командной строке, запускаются на удаленном компьютере, а результаты отображаются на локальном компьютере. Any commands that you type at the prompt run on the remote computer and the results are displayed on the local computer.

Чтобы завершить интерактивный сеанс, введите: To end the interactive session, type:

См. дополнительные сведения о командлетах Enter-PSSession и Exit-PSSession: For more information about the Enter-PSSession and Exit-PSSession cmdlets, see:

Выполнение удаленной команды Run a Remote Command

Чтобы выполнить команду на одном или нескольких компьютерах, используйте командлет Invoke-Command. To run a command on one or more computers, use the Invoke-Command cmdlet. Например, чтобы выполнить команду Get-UICulture на удаленных компьютерах Server01 и Server02, введите: For example, to run a Get-UICulture command on the Server01 and Server02 remote computers, type:

Выходные данные будут возвращены на ваш компьютер. The output is returned to your computer.

Запуск сценария Run a Script

Чтобы запустить скрипт на одном или нескольких удаленных компьютерах, используйте параметр FilePath командлета Invoke-Command . To run a script on one or many remote computers, use the FilePath parameter of the Invoke-Command cmdlet. Сценарий должен быть включен или доступен для локального компьютера. The script must be on or accessible to your local computer. Результаты будут возвращены на локальный компьютер. The results are returned to your local computer.

Например, следующая команда выполняет скрипт DiskCollect.ps1 на удаленных компьютерах Server01 и Server02. For example, the following command runs the DiskCollect.ps1 script on the remote computers, Server01 and Server02.

Установка постоянного подключения Establish a Persistent Connection

Используйте командлет New-PSSession для создания постоянного сеанса на удаленном компьютере. Use the New-PSSession cmdlet to create a persistent session on a remote computer. В следующем примере создаются удаленные сеансы на удаленных компьютерах Server01 и Server02. The following example creates remote sessions on Server01 and Server02. Объекты сеанса хранятся в переменной $s . The session objects are stored in the $s variable.

После установки сеансов в них можно выполнить любую команду. Now that the sessions are established, you can run any command in them. Так как сеансы являются постоянными, вы можете собирать данные из одной команды и использовать их в другой. And because the sessions are persistent, you can collect data from one command and use it in another command.

Например, следующая команда выполняет команду Get-Hotfix в сеансах в переменной $s и сохраняет результаты в переменной $h. For example, the following command runs a Get-HotFix command in the sessions in the $s variable and it saves the results in the $h variable. Переменная $h создается в каждом сеансе в переменной $s, но она не существует в локальном сеансе. The $h variable is created in each of the sessions in $s, but it doesn’t exist in the local session.

Читайте также:  What is ldap authentication in linux

Теперь вы можете использовать данные в переменной $h с другими командами в том же сеансе. Now you can use the data in the $h variable with other commands in the same session. Результаты отобразятся на локальном компьютере. The results are displayed on the local computer. Пример: For example:

Расширенная служба удаленного взаимодействия Advanced Remoting

Это и есть служба удаленного взаимодействия Windows PowerShell. Windows PowerShell remote management just begins here. Используя командлеты, установленные с Windows PowerShell, можно установить и настроить удаленные сеансы с локальных и удаленных компьютеров, создать настраиваемые и ограниченные сеансы, разрешить пользователям импортировать команды из удаленного сеанса, которые могут неявно выполняться в удаленном сеансе, настроить безопасность удаленного сеанса и многое другое. By using the cmdlets installed with Windows PowerShell, you can establish and configure remote sessions both from the local and remote ends, create customized and restricted sessions, allow users to import commands from a remote session that actually run implicitly on the remote session, configure the security of a remote session, and much more.

Windows PowerShell включает поставщик WSMan. Windows PowerShell includes a WSMan provider. Поставщик создает диск WSMAN: , который позволяет перемещаться по иерархии параметров конфигурации на локальном и удаленном компьютерах. The provider creates a WSMAN: drive that lets you navigate through a hierarchy of configuration settings on the local computer and remote computers.

См. дополнительные сведения о поставщике WSMan и командлетах WS-Management или введите команду Get-Help wsman в консоли Windows PowerShell. For more information about the WSMan provider, see WSMan Provider and About WS-Management Cmdlets, or in the Windows PowerShell console, type Get-Help wsman .

Дополнительные сведения можно найти в разделе For more information, see:

Справку по ошибкам службы удаленного взаимодействия см. в разделе about_Remote_Troubleshooting. For help with remoting errors, see about_Remote_Troubleshooting.

Добавление и вызов команд Adding and invoking commands

После создания пространства выполнения можно добавить в конвейер Повершеллкоммандс и скрипты Windows, а затем вызывать конвейер синхронно или асинхронно. After creating a runspace, you can add Windows PowerShellcommands and scripts to a pipeline, and then invoke the pipeline synchronously or asynchronously.

Создание конвейера Creating a pipeline

Класс System. Management. Automation. PowerShell предоставляет несколько методов для добавления команд, параметров и скриптов в конвейер. The System.Management.Automation.Powershell class provides several methods to add commands, parameters, and scripts to the pipeline. Конвейер можно вызвать синхронно, вызвав перегрузку метода System. Management. Automation. PowerShell. Invoke * или асинхронно, вызвав перегрузку метода System. Management. Automation. PowerShell. BeginInvoke * , а затем метод System. Management. Automation. PowerShell. EndInvoke * . You can invoke the pipeline synchronously by calling an overload of the System.Management.Automation.Powershell.Invoke* method, or asynchronously by calling an overload of the System.Management.Automation.Powershell.Begininvoke* and then the System.Management.Automation.Powershell.Endinvoke* method.

AddCommand AddCommand

Добавьте команду, которую требуется выполнить. Add the command that you want to execute.

Вызовите команду. Invoke the command.

Если метод System. Management. Automation. PowerShell. AddCommand * вызывается более одного раза перед вызовом метода System. Management. Automation. PowerShell. Invoke * , результат первой команды передается второму и т. д. If you call the System.Management.Automation.Powershell.Addcommand* method more than once before you call the System.Management.Automation.Powershell.Invoke* method, the result of the first command is piped to the second, and so on. Если вы не хотите передавать результат предыдущей команды команде, добавьте ее, вызвав метод System. Management. Automation. PowerShell. аддстатемент * . If you do not want to pipe the result of a previous command to a command, add it by calling the System.Management.Automation.Powershell.Addstatement* instead.

Читайте также:  Отредактировав файл hosts windows

аддпараметер AddParameter

В предыдущем примере выполняется одна команда без параметров. The previous example executes a single command without any parameters. Можно добавить параметры в команду с помощью метода System. Management. Automation. пскомманд. аддпараметер *. например, следующий код возвращает список всех процессов, именованных PowerShell на компьютере. You can add parameters to the command by using the System.Management.Automation.Pscommand.Addparameter* method For example, the following code gets a list of all of the processes that are named PowerShell running on the machine.

Можно добавить дополнительные параметры путем многократного вызова System. Management. Automation. пскомманд. аддпараметер * . You can add additional parameters by calling System.Management.Automation.Pscommand.Addparameter* repeatedly.

Также можно добавить словарь имен и значений параметров, вызвав метод System. Management. Automation. PowerShell. аддпараметерс * . You can also add a dictionary of parameter names and values by calling the System.Management.Automation.Powershell.Addparameters* method.

аддстатемент AddStatement

Пакетную обработку можно имитировать с помощью метода System. Management. Automation. PowerShell. аддстатемент * , который добавляет дополнительный оператор в конец конвейера. следующий код возвращает список запущенных процессов с именем PowerShell , а затем получает список запущенных служб. You can simulate batching by using the System.Management.Automation.Powershell.Addstatement* method, which adds an additional statement to the end of the pipeline The following code gets a list of running processes with the name PowerShell , and then gets the list of running services.

аддскрипт AddScript

Можно запустить существующий скрипт, вызвав метод System. Management. Automation. PowerShell. аддскрипт * . You can run an existing script by calling the System.Management.Automation.Powershell.Addscript* method. В следующем примере в конвейер добавляется скрипт и выполняется его выполнение. The following example adds a script to the pipeline and runs it. В этом примере предполагается, что в папке уже есть скрипт с именем MyScript.ps1 D:\PSScripts . This example assumes there is already a script named MyScript.ps1 in a folder named D:\PSScripts .

Существует также версия метода System. Management. Automation. PowerShell. аддскрипт * , принимающая логический параметр с именем useLocalScope . There is also a version of the System.Management.Automation.Powershell.Addscript* method that takes a boolean parameter named useLocalScope . Если этот параметр имеет значение true , скрипт выполняется в локальной области. If this parameter is set to true , then the script is run in the local scope. Следующий код запустит скрипт в локальной области. The following code will run the script in the local scope.

Синхронный вызов конвейера Invoking a pipeline synchronously

После добавления элементов в конвейер вы вызываете его. After you add elements to the pipeline, you invoke it. Для синхронного вызова конвейера вызывается перегрузка метода System. Management. Automation. PowerShell. Invoke * . To invoke the pipeline synchronously, you call an overload of the System.Management.Automation.Powershell.Invoke* method. В следующем примере показано, как синхронно вызвать конвейер. The following example shows how to synchronously invoke a pipeline.

Асинхронный вызов конвейера Invoking a pipeline asynchronously

Асинхронный вызов конвейера вызывает перегрузку System. Management. Automation. PowerShell. BeginInvoke * для создания объекта IAsyncResult и последующего вызова метода System. Management. Automation. PowerShell. EndInvoke * . You invoke a pipeline asynchronously by calling an overload of the System.Management.Automation.Powershell.Begininvoke* to create an IAsyncResult object, and then calling the System.Management.Automation.Powershell.Endinvoke* method.

В следующем примере показано, как вызвать конвейер асинхронно. The following example shows how to invoke a pipeline asynchronously.

Оцените статью