Home > Backend Development > C++ > How to Pass Command-Line Arguments to PowerShell Scripts from C#?

How to Pass Command-Line Arguments to PowerShell Scripts from C#?

DDD
Release: 2025-01-23 23:01:13
Original
575 people have browsed it

How to Pass Command-Line Arguments to PowerShell Scripts from C#?

Execute PowerShell scripts with parameters in C#

To execute a PowerShell script in C# and provide command line arguments, you can follow these steps:

  1. Configuring Runspace: Create a RunspaceConfiguration and use it to instantiate a Runspace object. This object represents the PowerShell runtime environment.
  2. Create a PowerShell command: Use the Command constructor to convert the script file path to a Command object.
  3. Add command line parameters: Use the CommandParameter constructor to create a CommandParameter for each parameter. Add these parameters to the Command's Parameter collection.
  4. Building the pipeline: Add the Command object to the Pipeline's Commands collection.
  5. Execute the script: Call Pipeline's Invoke method to execute the script and process its output.

Code example:

<code class="language-csharp">// 配置和 Runspace
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();

// 带参数的 PowerShell 命令
Command myCommand = new Command(scriptfile);
CommandParameter testParam = new CommandParameter("key", "value");
myCommand.Parameters.Add(testParam);

// 管道和执行
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.Add(myCommand);
var results = pipeline.Invoke();</code>
Copy after login

By following these steps, you can efficiently pass command line parameters from C# to a PowerShell script and properly handle spaces in parameter values.

The above is the detailed content of How to Pass Command-Line Arguments to PowerShell Scripts from C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template