Home >Backend Development >C++ >How to Pass Command-Line Arguments with Spaces to PowerShell Scripts from C#?
Integrating PowerShell scripts into C# applications provides powerful automation capabilities. However, handling command-line arguments containing spaces can be tricky. This article demonstrates a robust method for executing PowerShell scripts from C#, reliably passing arguments with embedded spaces.
The common approach of directly passing arguments often fails when spaces are present. The solution lies in using the PowerShell Command
and CommandParameter
objects to properly manage argument construction.
Here's a refined approach to execute a PowerShell script from C# with arguments, even those containing spaces:
Runspace
to manage the PowerShell execution environment.Command
object specifying the path to your PowerShell script.CommandParameter
objects to add arguments. This correctly handles spaces and special characters. Each CommandParameter
takes the argument name and its value.Command
object to a Pipeline
.Here's an improved code example reflecting these steps:
<code class="language-csharp">RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); // Path to your PowerShell script string scriptFile = "path/to/your/script.ps1"; // Create the Command object Command myCommand = new Command(scriptFile); // Add parameters with spaces handled correctly myCommand.Parameters.Add(new CommandParameter("key1", "value with spaces")); myCommand.Parameters.Add(new CommandParameter("key2", "another value")); // Add the command to the pipeline pipeline.Commands.Add(myCommand); // Invoke the pipeline and handle the results Collection<PSObject> results = pipeline.Invoke(); // Process the results as needed foreach (PSObject result in results) { // ... handle each result ... } runspace.Close();</code>
This approach ensures that command-line arguments, regardless of whether they contain spaces, are correctly passed to your PowerShell script, enabling seamless integration between C# and PowerShell. Remember to replace "path/to/your/script.ps1"
with the actual path to your script.
The above is the detailed content of How to Pass Command-Line Arguments with Spaces to PowerShell Scripts from C#?. For more information, please follow other related articles on the PHP Chinese website!