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?
For me, the most flexible way to run PowerShell script from C# was using PowerShell.Create().AddScript()
The snippet of the code is
You can check if there's any error by checking Streams.Error. It was really handy to check the collection. User is the type of object the PowerShell script returns.