Running windows command from powershell

Содержание
  1. Запуск Windows PowerShell Starting Windows PowerShell
  2. В PowerShell Core есть переименованный двоичный файл PowerShell Core has renamed binary
  3. Запуск Windows PowerShell в более ранних версиях Windows How to Start Windows PowerShell on Earlier Versions of Windows
  4. Из меню «Пуск» From the Start Menu
  5. В командной строке At the Command Prompt
  6. С правами администратора (Запуск от имени администратора) With Administrative privileges (Run as administrator)
  7. Запуск интегрированной среды сценариев Windows PowerShell в более ранних версиях Windows How to Start Windows PowerShell ISE on Earlier Releases of Windows
  8. Из меню «Пуск» From the Start Menu
  9. В командной строке At the Command Prompt
  10. С правами администратора (Запуск от имени администратора) With Administrative privileges (Run as administrator)
  11. Включение интегрированной среды сценариев Windows PowerShell в более ранних версиях Windows How to Enable Windows PowerShell ISE on Earlier Releases of Windows
  12. Включение интегрированной среды сценариев Windows PowerShell Windows PowerShell (ISE) To enable Windows PowerShell Integrated Scripting Environment (ISE)
  13. Запуск 32-разрядной версии Windows PowerShell Starting the 32-Bit Version of Windows PowerShell
  14. Выполнение удаленных команд Running Remote Commands
  15. Удаленное взаимодействие с Windows PowerShell без настройки Windows PowerShell Remoting Without Configuration
  16. Служба удаленного взаимодействия Windows PowerShell Windows PowerShell Remoting
  17. Запуск интерактивного сеанса Start an Interactive Session
  18. Выполнение удаленной команды Run a Remote Command
  19. Запуск сценария Run a Script
  20. Установка постоянного подключения Establish a Persistent Connection
  21. Расширенная служба удаленного взаимодействия Advanced Remoting

Запуск Windows PowerShell Starting Windows PowerShell

Windows PowerShell — это обработчик скриптов .DLL , который внедрен в несколько узлов. Windows PowerShell is a scripting engine .DLL that’s embedded into multiple hosts. Самый распространенный запускаемый узел — интерактивная командная строка powershell.exe и интерактивная среда скриптов powershell_ise.exe . The most common hosts you’ll start are the interactive command-line powershell.exe and the Interactive Scripting Environment powershell_ise.exe .

Информацию о запуске Windows PowerShell® в Windows Server® 2012 R2, Windows® 8.1, Windows Server 2012 и Windows 8 см. в статье Общие задачи управления и навигации в Windows. To start Windows PowerShell® on Windows Server® 2012 R2, Windows® 8.1, Windows Server 2012, and Windows 8, see Common Management Tasks and Navigation in Windows.

В PowerShell Core есть переименованный двоичный файл PowerShell Core has renamed binary

PowerShell Core, или PowerShell, имеет версию 6 и выше с открытым исходным кодом и использует .NET Core. PowerShell Core, referred to as PowerShell, is version 6 and higher that’s open source and uses .NET Core. Поддерживаемые версии доступны в Windows, macOS и Linux. Supported versions are available on Windows, macOS, and Linux.

Начиная с PowerShell 6 двоичный файл PowerShell был переименован в pwsh.exe для Windows и pwsh для macOS и Linux. Beginning in PowerShell 6, the PowerShell binary was renamed pwsh.exe for Windows and pwsh for macOS and Linux. Вы можете запустить предварительную версию PowerShell с помощью pwsh-preview . You can start PowerShell preview versions using pwsh-preview . Дополнительные сведения см. в разделе Новые возможности в PowerShell Core 6.0 и Сведения о pwsh. For more information, see What’s New in PowerShell Core 6.0 and About pwsh.

Чтобы найти справку по командлетам и документацию по установке для PowerShell 7, воспользуйтесь следующими ссылками: To find cmdlet reference and installation documentation for PowerShell 7, use the following links:

Документ Document Ссылка Link
Справка по командлетам Cmdlet reference Обозреватель модулей PowerShell PowerShell Module Browser
Установка в Windows Windows installation Установка PowerShell Core в Windows Installing PowerShell Core on Windows
Установка в macOS macOS installation Установка PowerShell Core в macOS Installing PowerShell Core on macOS
Установка в Linux Linux installation Установка PowerShell Core в Linux Installing PowerShell Core on Linux

Сведения о других версиях PowerShell см. в документации по использованию PowerShell. To view content for other PowerShell versions, see How to use the PowerShell documentation.

Запуск Windows PowerShell в более ранних версиях Windows How to Start Windows PowerShell on Earlier Versions of Windows

В этом разделе объясняется, как запустить Windows PowerShell и интегрированную среду скриптов Windows PowerShell (ISE) в Windows® 7, Windows Server® 2008 R2 и Windows Server® 2008. This section explains how to start Windows PowerShell and Windows PowerShell Integrated Scripting Environment (ISE) on Windows® 7, Windows Server® 2008 R2, and Windows Server® 2008. Кроме того, здесь поясняется, как включить дополнительный компонент Windows PowerShell ISE в Windows PowerShell 2.0 в ОС Windows Server® 2008 R2 и Windows Server® 2008. It also explains how to enable the optional feature for Windows PowerShell ISE in Windows PowerShell 2.0 on Windows Server® 2008 R2 and Windows Server® 2008.

Используйте любой из следующих методов для запуска установленной версии Windows PowerShell 3.0 или Windows PowerShell 4.0, где это возможно. Use any of the following methods to start the installed version of Windows PowerShell 3.0, or Windows PowerShell 4.0, where applicable.

Из меню «Пуск» From the Start Menu

  • Нажмите кнопку Пуск , введите PowerShell и выберите Windows PowerShell. Click Start , type PowerShell , and then click Windows PowerShell.
  • В меню Пуск выберите Пуск , Все программы , Стандартные , откройте папку Windows PowerShell и щелкните Windows PowerShell. From the Start menu, click Start , click All Programs , click Accessories , click the Windows PowerShell folder, and then click Windows PowerShell.

В командной строке At the Command Prompt

В cmd.exe , Windows PowerShell или интегрированной среде сценариев Windows PowerShell для запуска Windows PowerShell введите следующее: In cmd.exe , Windows PowerShell, or Windows PowerShell ISE, to start Windows PowerShell, type:

Можно также использовать параметры программы powershell.exe для настройки сеанса. You can also use the parameters of the powershell.exe program to customize the session. Дополнительные сведения см. в статье Справка по командной строке PowerShell.exe. For more information, see PowerShell.exe Command-Line Help.

С правами администратора (Запуск от имени администратора) With Administrative privileges (Run as administrator)

Нажмите кнопку Пуск , введите PowerShell , щелкните правой кнопкой мыши Windows PowerShell и выберите пункт Запуск от имени администратора. Click Start , type PowerShell , right-click Windows PowerShell , and then click Run as administrator.

Запуск интегрированной среды сценариев Windows PowerShell в более ранних версиях Windows How to Start Windows PowerShell ISE on Earlier Releases of Windows

Используйте один из следующих методов для запуска интегрированной среды сценариев Windows PowerShell. Use any of the following methods to start Windows PowerShell ISE.

Из меню «Пуск» From the Start Menu

  • Нажмите кнопку Пуск , введите Интегрированная среда сценариев и выберите Интегрированная среда сценариев Windows PowerShell. Click Start , type ISE , and then click Windows PowerShell ISE.
  • В меню Пуск выберите Пуск , Все программы , Стандартные , откройте папку Windows PowerShell и щелкните Интегрированная среда сценариев Windows PowerShell. From the Start menu, click Start , click All Programs , click Accessories , click the Windows PowerShell folder, and then click Windows PowerShell ISE.

В командной строке At the Command Prompt

В cmd.exe , Windows PowerShell или интегрированной среде сценариев Windows PowerShell для запуска Windows PowerShell введите следующее: In cmd.exe , Windows PowerShell, or Windows PowerShell ISE, to start Windows PowerShell, type:

С правами администратора (Запуск от имени администратора) With Administrative privileges (Run as administrator)

Нажмите кнопку Пуск , введите Интегрированная среда сценариев , щелкните правой кнопкой мыши Интегрированная среда сценариев Windows PowerShell и выберите пункт Запуск от имени администратора. Click Start , type ISE , right-click Windows PowerShell ISE , and then click Run as administrator.

Включение интегрированной среды сценариев Windows PowerShell в более ранних версиях Windows How to Enable Windows PowerShell ISE on Earlier Releases of Windows

При использовании Windows PowerShell 4.0 и Windows PowerShell 3.0 интегрированная среда сценариев Windows PowerShell по умолчанию включена во всех версиях Windows. In Windows PowerShell 4.0 and Windows PowerShell 3.0, Windows PowerShell ISE is enabled by default on all versions of Windows. Если она еще не включена, Windows Management Framework 4.0 или Windows Management Framework 3.0 включает ее. If it isn’t already enabled, Windows Management Framework 4.0 or Windows Management Framework 3.0 enables it.

При использовании Windows PowerShell 2.0 интегрированная среда сценариев Windows PowerShell по умолчанию включена в Windows 7. In Windows PowerShell 2.0, Windows PowerShell ISE is enabled by default on Windows 7. В Windows Server 2008 R2 и Windows Server 2008 эта функция является дополнительной. However, on Windows Server 2008 R2 and Windows Server 2008, it’s an optional feature.

Чтобы включить интегрированную среду сценариев Windows PowerShell для Windows PowerShell 2.0 в Windows Server 2008 R2 или Windows Server 2008, выполните указанные ниже действия. To enable Windows PowerShell ISE in Windows PowerShell 2.0 on Windows Server 2008 R2 or Windows Server 2008, use the following procedure.

Включение интегрированной среды сценариев Windows PowerShell Windows PowerShell (ISE) To enable Windows PowerShell Integrated Scripting Environment (ISE)

  1. Запустите диспетчер серверов. Start Server Manager.
  2. Щелкните Компоненты и выберите Добавить компоненты. Click Features and then click Add Features.
  3. В меню «Выберите компоненты» щелкните интегрированную среду сценариев Windows PowerShell. In Select Features, click Windows PowerShell Integrated Scripting Environment (ISE).

Запуск 32-разрядной версии Windows PowerShell Starting the 32-Bit Version of Windows PowerShell

При установке Windows PowerShell на 64-разрядном компьютере в дополнение к 64-разрядной версии устанавливается Windows PowerShell (x86) — 32-разрядная версия Windows PowerShell. When you install Windows PowerShell on a 64-bit computer, Windows PowerShell (x86) , a 32-bit version of Windows PowerShell is installed in addition to the 64-bit version. При открытии Windows PowerShell по умолчанию запускается 64-разрядная версия. When you run Windows PowerShell, the 64-bit version runs by default.

Однако в некоторых случаях нужно запустить Windows PowerShell (x86) , например при использовании модуля, которому требуется 32-разрядная версия, или при удаленном подключении к 32-разрядному компьютеру. However, you might occasionally need to run Windows PowerShell (x86) , such as when you’re using a module that requires the 32-bit version or when you’re connecting remotely to a 32-bit computer.

Для запуска 32-разрядной версии Windows PowerShell воспользуйтесь любой из следующих процедур. To start a 32-bit version of Windows PowerShell, use any of the following procedures.

Выполнение удаленных команд 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.

Запуск интерактивного сеанса 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.

Теперь вы можете использовать данные в переменной $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.

Читайте также:  Linux mint настройка питания
Оцените статью