Execute PowerShell scripts with parameters in C#
To execute a PowerShell script in C# and provide command line arguments, you can follow these steps:
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>
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!