I need to execute a PowerShell script from within C#. The script needs commandline arguments.
This is what I have done so far:
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.Add(scriptFile); // Execute PowerShell script results = pipeline.Invoke();
scriptFile contains something like ‘C:\Program Files\MyProgram\Whatever.ps1’.
The script uses a commandline argument such as ‘-key Value’ whereas Value can be something like a path that also might contain spaces.
I don’t get this to work. Does anyone know how to pass commandline arguments to a PowerShell script from within C# and make sure that spaces are no problem?
Try creating scriptfile as a separate command:
then you can add parameters with
and finally
Here is the complete, edited code: