Integrating the ability to execute PowerShell scripts in C# applications can bring many advantages. However, to take full advantage of this feature, it's important to understand how to pass command line parameters to PowerShell scripts in C# code. This guide will explore this common scenario and provide a comprehensive solution to help you achieve seamless execution of PowerShell scripts and parameters.
To execute a PowerShell script from C#, you might use the following code template:
<code class="language-csharp">RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.Add(scriptFile); results = pipeline.Invoke();</code>
In this code, scriptFile
represents the path to the PowerShell script (for example, "C:Program FilesMyProgramWhatever.ps1"). If your script uses command line arguments in the "-key Value" format (where Value can contain spaces), you may have difficulty passing these arguments effectively.
To solve this problem, you need to build a separate command object for the script file and specify the parameters using the CommandParameter
object:
<code class="language-csharp">Command myCommand = new Command(scriptfile); CommandParameter testParam = new CommandParameter("key", "value"); myCommand.Parameters.Add(testParam); pipeline.Commands.Add(myCommand);</code>
This method ensures correct handling of command line arguments, including arguments containing spaces.
To summarize, here is the complete modified code containing the solution:
<code class="language-csharp">RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); // 使用参数构建单独的命令 Command myCommand = new Command(scriptfile); CommandParameter testParam = new CommandParameter("key", "value"); myCommand.Parameters.Add(testParam); pipeline.Commands.Add(myCommand); results = pipeline.Invoke();</code>
By integrating this solution into your C# code, you will be able to confidently execute PowerShell scripts and pass command line arguments, even if the arguments contain spaces. This enhanced functionality will enable you to seamlessly integrate PowerShell scripts into your C# applications.
The above is the detailed content of How Can I Pass Command Line Arguments to PowerShell Scripts from C#?. For more information, please follow other related articles on the PHP Chinese website!