Windows powershell execute exe

Содержание
  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. About PowerShell.exe
  15. Short Description
  16. Long Description
  17. SYNTAX
  18. Parameters
  19. -PSConsoleFile
  20. -Version
  21. -NoLogo
  22. -NoExit
  23. -NoProfile
  24. -NonInteractive
  25. -InputFormat Describes the format of data sent to PowerShell. Valid values are «Text» (text strings) or «XML» (serialized CLIXML format). -OutputFormat Determines how output from PowerShell is formatted. Valid values are «Text» (text strings) or «XML» (serialized CLIXML format). -WindowStyle Sets the window style for the session. Valid values are Normal, Minimized, Maximized and Hidden. -EncodedCommand Accepts a base-64-encoded string version of a command. Use this parameter to submit commands to PowerShell that require complex quotation marks or curly braces. The string must be formatted using UTF-16LE character encoding. -ConfigurationName Specifies a configuration endpoint in which PowerShell is run. This can be any endpoint registered on the local machine including the default PowerShell remoting endpoints or a custom endpoint having specific user role capabilities. If the value of File is «-«, the command text is read from standard input. Running powershell -File — without redirected standard input starts a regular session. This is the same as not specifying the File parameter at all. If the value of File is a file path, the script runs in the local scope («dot-sourced»), so that the functions and variables that the script creates are available in the current session. Enter the script file path and any parameters. File must be the last parameter in the command. All values typed after the File parameter are interpreted as the script file path and parameters passed to that script. Parameters passed to the script are passed as literal strings, after interpretation by the current shell. For example, if you are in cmd.exe and want to pass an environment variable value, you would use the cmd.exe syntax: powershell.exe -File .\test.ps1 -TestParam %windir% In contrast, running powershell.exe -File .\test.ps1 -TestParam $env:windir in cmd.exe results in the script receiving the literal string $env:windir because it has no special meaning to the current cmd.exe shell. The $env:windir style of environment variable reference can be used inside a Command parameter, since there it will be interpreted as PowerShell code. Similarly, if you want to execute the same command from a Batch script, you would use % dp0 instead of .\ or $PSScriptRoot to represent the current execution directory: powershell.exe -File % dp0test.ps1 -TestParam %windir% . If you instead used .\test.ps1 , PowerShell would throw an error because it cannot find the literal path .\test.ps1 When the value of File is a file path, File must be the last parameter in the command because any characters typed after the File parameter name are interpreted as the script file path followed by the script parameters. You can include the script parameters and values in the value of the File parameter. For example: -File .\Get-Script.ps1 -Domain Central Typically, the switch parameters of a script are either included or omitted. For example, the following command uses the All parameter of the Get-Script.ps1 script file: -File .\Get-Script.ps1 -All In rare cases, you might need to provide a Boolean value for a parameter. It is not possible to pass an explicit boolean value for a switch parameter when running a script in this way. This limitation was removed in PowerShell 6 ( pwsh.exe ). -ExecutionPolicy Sets the default execution policy for the current session and saves it in the $env:PSExecutionPolicyPreference environment variable. This parameter does not change the PowerShell execution policy that is set in the registry. For information about PowerShell execution policies, including a list of valid values, see about_Execution_Policies. -Command Executes the specified commands (and any parameters) as though they were typed at the PowerShell command prompt, and then exits, unless the NoExit parameter is specified. The value of Command can be — , a script block, or a string. If the value of Command is — , the command text is read from standard input. The Command parameter only accepts a script block for execution when it can recognize the value passed to Command as a ScriptBlock type. This is only possible when running powershell.exe from another PowerShell host. The ScriptBlock type may be contained in an existing variable, returned from an expression, or parsed by the PowerShell host as a literal script block enclosed in curly braces ( <> ), before being passed to powershell.exe . In cmd.exe , there is no such thing as a script block (or ScriptBlock type), so the value passed to Command will always be a string. You can write a script block inside the string, but instead of being executed it will behave exactly as though you typed it at a typical PowerShell prompt, printing the contents of the script block back out to you. A string passed to Command is still executed as PowerShell code, so the script block curly braces are often not required in the first place when running from cmd.exe . To execute an inline script block defined inside a string, the call operator & can be used: If the value of Command is a string, Command must be the last parameter for pwsh, because all arguments following it are interpreted as part of the command to execute. When called from within an existing PowerShell session, the results are returned to the parent shell as deserialized XML objects, not live objects. For other shells, the results are returned as strings. If the value of Command is — , the command text is read from standard input. You must redirect standard input when using the Command parameter with standard input. For example: This example produces the following output: The process exit code is determined by status of the last (executed) command within the script block. The exit code is 0 when $? is $true or 1 when $? is $false . If the last command is an external program or a PowerShell script that explicitly sets an exit code other than 0 or 1 , that exit code is converted to 1 for process exit code. To preserve the specific exit code, add exit $LASTEXITCODE to your command string or script block. Similarly, the value 1 is returned when a script-terminating (runspace-terminating) error, such as a throw or -ErrorAction Stop , occurs or when execution is interrupted with Ctrl — C . Displays help for PowerShell.exe. If you are typing a PowerShell.exe command in a PowerShell session, prepend the command parameters with a hyphen (-), not a forward slash (/). You can use either a hyphen or forward slash in cmd.exe. REMARKS Troubleshooting note: In PowerShell 2.0, starting some programs from the PowerShell console fails with a LastExitCode of 0xc0000142.
  26. -OutputFormat Determines how output from PowerShell is formatted. Valid values are «Text» (text strings) or «XML» (serialized CLIXML format). -WindowStyle Sets the window style for the session. Valid values are Normal, Minimized, Maximized and Hidden. -EncodedCommand Accepts a base-64-encoded string version of a command. Use this parameter to submit commands to PowerShell that require complex quotation marks or curly braces. The string must be formatted using UTF-16LE character encoding. -ConfigurationName Specifies a configuration endpoint in which PowerShell is run. This can be any endpoint registered on the local machine including the default PowerShell remoting endpoints or a custom endpoint having specific user role capabilities. If the value of File is «-«, the command text is read from standard input. Running powershell -File — without redirected standard input starts a regular session. This is the same as not specifying the File parameter at all. If the value of File is a file path, the script runs in the local scope («dot-sourced»), so that the functions and variables that the script creates are available in the current session. Enter the script file path and any parameters. File must be the last parameter in the command. All values typed after the File parameter are interpreted as the script file path and parameters passed to that script. Parameters passed to the script are passed as literal strings, after interpretation by the current shell. For example, if you are in cmd.exe and want to pass an environment variable value, you would use the cmd.exe syntax: powershell.exe -File .\test.ps1 -TestParam %windir% In contrast, running powershell.exe -File .\test.ps1 -TestParam $env:windir in cmd.exe results in the script receiving the literal string $env:windir because it has no special meaning to the current cmd.exe shell. The $env:windir style of environment variable reference can be used inside a Command parameter, since there it will be interpreted as PowerShell code. Similarly, if you want to execute the same command from a Batch script, you would use % dp0 instead of .\ or $PSScriptRoot to represent the current execution directory: powershell.exe -File % dp0test.ps1 -TestParam %windir% . If you instead used .\test.ps1 , PowerShell would throw an error because it cannot find the literal path .\test.ps1 When the value of File is a file path, File must be the last parameter in the command because any characters typed after the File parameter name are interpreted as the script file path followed by the script parameters. You can include the script parameters and values in the value of the File parameter. For example: -File .\Get-Script.ps1 -Domain Central Typically, the switch parameters of a script are either included or omitted. For example, the following command uses the All parameter of the Get-Script.ps1 script file: -File .\Get-Script.ps1 -All In rare cases, you might need to provide a Boolean value for a parameter. It is not possible to pass an explicit boolean value for a switch parameter when running a script in this way. This limitation was removed in PowerShell 6 ( pwsh.exe ). -ExecutionPolicy Sets the default execution policy for the current session and saves it in the $env:PSExecutionPolicyPreference environment variable. This parameter does not change the PowerShell execution policy that is set in the registry. For information about PowerShell execution policies, including a list of valid values, see about_Execution_Policies. -Command Executes the specified commands (and any parameters) as though they were typed at the PowerShell command prompt, and then exits, unless the NoExit parameter is specified. The value of Command can be — , a script block, or a string. If the value of Command is — , the command text is read from standard input. The Command parameter only accepts a script block for execution when it can recognize the value passed to Command as a ScriptBlock type. This is only possible when running powershell.exe from another PowerShell host. The ScriptBlock type may be contained in an existing variable, returned from an expression, or parsed by the PowerShell host as a literal script block enclosed in curly braces ( <> ), before being passed to powershell.exe . In cmd.exe , there is no such thing as a script block (or ScriptBlock type), so the value passed to Command will always be a string. You can write a script block inside the string, but instead of being executed it will behave exactly as though you typed it at a typical PowerShell prompt, printing the contents of the script block back out to you. A string passed to Command is still executed as PowerShell code, so the script block curly braces are often not required in the first place when running from cmd.exe . To execute an inline script block defined inside a string, the call operator & can be used: If the value of Command is a string, Command must be the last parameter for pwsh, because all arguments following it are interpreted as part of the command to execute. When called from within an existing PowerShell session, the results are returned to the parent shell as deserialized XML objects, not live objects. For other shells, the results are returned as strings. If the value of Command is — , the command text is read from standard input. You must redirect standard input when using the Command parameter with standard input. For example: This example produces the following output: The process exit code is determined by status of the last (executed) command within the script block. The exit code is 0 when $? is $true or 1 when $? is $false . If the last command is an external program or a PowerShell script that explicitly sets an exit code other than 0 or 1 , that exit code is converted to 1 for process exit code. To preserve the specific exit code, add exit $LASTEXITCODE to your command string or script block. Similarly, the value 1 is returned when a script-terminating (runspace-terminating) error, such as a throw or -ErrorAction Stop , occurs or when execution is interrupted with Ctrl — C . Displays help for PowerShell.exe. If you are typing a PowerShell.exe command in a PowerShell session, prepend the command parameters with a hyphen (-), not a forward slash (/). You can use either a hyphen or forward slash in cmd.exe. REMARKS Troubleshooting note: In PowerShell 2.0, starting some programs from the PowerShell console fails with a LastExitCode of 0xc0000142.
  27. -WindowStyle
  28. -EncodedCommand
  29. -ConfigurationName
  30. -ExecutionPolicy
  31. -Command
  32. REMARKS
Читайте также:  Требуемое устройство не подключено или недоступно 0xc000000e windows 10

Запуск 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.

Читайте также:  Windows 10 enable bluetooth

Чтобы найти справку по командлетам и документацию по установке для 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.

About PowerShell.exe

Short Description

Explains how to use the powershell.exe command-line interface. Displays the command-line parameters and describes the syntax.

Long Description

SYNTAX

Parameters

-PSConsoleFile

Loads the specified PowerShell console file. Enter the path and name of the console file. To create a console file, use the Export-Console cmdlet in PowerShell.

-Version

Starts the specified version of PowerShell. Valid values are 2.0 and 3.0. The version that you specify must be installed on the system. If Windows PowerShell 3.0 is installed on the computer, «3.0» is the default version. Otherwise, «2.0» is the default version. For more information, see Installing PowerShell.

Hides the copyright banner at startup.

-NoExit

Does not exit after running startup commands.

Starts PowerShell using a single-threaded apartment. In Windows PowerShell 2.0, multi-threaded apartment (MTA) is the default. In Windows PowerShell 3.0, single-threaded apartment (STA) is the default.

Starts PowerShell using a multi-threaded apartment. This parameter is introduced in PowerShell 3.0. In PowerShell 2.0, multi-threaded apartment (MTA) is the default. In PowerShell 3.0, single-threaded apartment (STA) is the default.

-NoProfile

Does not load the PowerShell profile.

-NonInteractive

Does not present an interactive prompt to the user.

-InputFormat

Describes the format of data sent to PowerShell. Valid values are «Text» (text strings) or «XML» (serialized CLIXML format).

-OutputFormat

Determines how output from PowerShell is formatted. Valid values are «Text» (text strings) or «XML» (serialized CLIXML format).

-WindowStyle

Sets the window style for the session. Valid values are Normal, Minimized, Maximized and Hidden.

-EncodedCommand

Accepts a base-64-encoded string version of a command. Use this parameter to submit commands to PowerShell that require complex quotation marks or curly braces. The string must be formatted using UTF-16LE character encoding.

-ConfigurationName

Specifies a configuration endpoint in which PowerShell is run. This can be any endpoint registered on the local machine including the default PowerShell remoting endpoints or a custom endpoint having specific user role capabilities.

If the value of File is «-«, the command text is read from standard input. Running powershell -File — without redirected standard input starts a regular session. This is the same as not specifying the File parameter at all.

If the value of File is a file path, the script runs in the local scope («dot-sourced»), so that the functions and variables that the script creates are available in the current session. Enter the script file path and any parameters. File must be the last parameter in the command. All values typed after the File parameter are interpreted as the script file path and parameters passed to that script.

Parameters passed to the script are passed as literal strings, after interpretation by the current shell. For example, if you are in cmd.exe and want to pass an environment variable value, you would use the cmd.exe syntax: powershell.exe -File .\test.ps1 -TestParam %windir%

In contrast, running powershell.exe -File .\test.ps1 -TestParam $env:windir in cmd.exe results in the script receiving the literal string $env:windir because it has no special meaning to the current cmd.exe shell. The $env:windir style of environment variable reference can be used inside a Command parameter, since there it will be interpreted as PowerShell code.

Similarly, if you want to execute the same command from a Batch script, you would use %

dp0 instead of .\ or $PSScriptRoot to represent the current execution directory: powershell.exe -File %

dp0test.ps1 -TestParam %windir% . If you instead used .\test.ps1 , PowerShell would throw an error because it cannot find the literal path .\test.ps1

When the value of File is a file path, File must be the last parameter in the command because any characters typed after the File parameter name are interpreted as the script file path followed by the script parameters.

You can include the script parameters and values in the value of the File parameter. For example: -File .\Get-Script.ps1 -Domain Central

Typically, the switch parameters of a script are either included or omitted. For example, the following command uses the All parameter of the Get-Script.ps1 script file: -File .\Get-Script.ps1 -All

In rare cases, you might need to provide a Boolean value for a parameter. It is not possible to pass an explicit boolean value for a switch parameter when running a script in this way. This limitation was removed in PowerShell 6 ( pwsh.exe ).

-ExecutionPolicy

Sets the default execution policy for the current session and saves it in the $env:PSExecutionPolicyPreference environment variable. This parameter does not change the PowerShell execution policy that is set in the registry. For information about PowerShell execution policies, including a list of valid values, see about_Execution_Policies.

-Command

Executes the specified commands (and any parameters) as though they were typed at the PowerShell command prompt, and then exits, unless the NoExit parameter is specified.

The value of Command can be — , a script block, or a string. If the value of Command is — , the command text is read from standard input.

The Command parameter only accepts a script block for execution when it can recognize the value passed to Command as a ScriptBlock type. This is only possible when running powershell.exe from another PowerShell host. The ScriptBlock type may be contained in an existing variable, returned from an expression, or parsed by the PowerShell host as a literal script block enclosed in curly braces ( <> ), before being passed to powershell.exe .

In cmd.exe , there is no such thing as a script block (or ScriptBlock type), so the value passed to Command will always be a string. You can write a script block inside the string, but instead of being executed it will behave exactly as though you typed it at a typical PowerShell prompt, printing the contents of the script block back out to you.

A string passed to Command is still executed as PowerShell code, so the script block curly braces are often not required in the first place when running from cmd.exe . To execute an inline script block defined inside a string, the call operator & can be used:

If the value of Command is a string, Command must be the last parameter for pwsh, because all arguments following it are interpreted as part of the command to execute.

When called from within an existing PowerShell session, the results are returned to the parent shell as deserialized XML objects, not live objects. For other shells, the results are returned as strings.

If the value of Command is — , the command text is read from standard input. You must redirect standard input when using the Command parameter with standard input. For example:

This example produces the following output:

The process exit code is determined by status of the last (executed) command within the script block. The exit code is 0 when $? is $true or 1 when $? is $false . If the last command is an external program or a PowerShell script that explicitly sets an exit code other than 0 or 1 , that exit code is converted to 1 for process exit code. To preserve the specific exit code, add exit $LASTEXITCODE to your command string or script block.

Similarly, the value 1 is returned when a script-terminating (runspace-terminating) error, such as a throw or -ErrorAction Stop , occurs or when execution is interrupted with Ctrl — C .

Displays help for PowerShell.exe. If you are typing a PowerShell.exe command in a PowerShell session, prepend the command parameters with a hyphen (-), not a forward slash (/). You can use either a hyphen or forward slash in cmd.exe.

REMARKS

Troubleshooting note: In PowerShell 2.0, starting some programs from the PowerShell console fails with a LastExitCode of 0xc0000142.

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