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?
Mine is a bit more smaller and simpler:
I have another solution. I just want to test if executing a PowerShell script succeeds, because perhaps somebody might change the policy. As the argument, I just specify the path of the script to be executed.
With the contents of the script being:
Try creating scriptfile as a separate command:
then you can add parameters with
and finally
Here is the complete, edited code:
Any chance I could get more clarity on the passing params to the Commands.AddScript method?
C:\Foo1.PS1 Hello World Hunger C:\Foo2.PS1 Hello World
scriptFile = "C:\Foo1.PS1"
parameters = "parm1 parm2 parm3" ... variable length of params
Resolved this ... passing null as the name and the param as value into a collection of CommandParameters
Here is my function:
You can also just use the pipeline with the AddScript Method:
It will take a string, and whatever parameters you pass it.
Here is a way to add Parameters to the script if you used
This is with using an HashMap as paramaters the key being the name of the variable in the script and the value is the value of the variable.
And the fill variable method is:
this way you can easily add multiple parameters to a script. I've also noticed that if you want to get a value from a variable in you script like so:
//results being the name of the v
you'll have to do it the way I showed because for some reason if you do it the way Kosi2801 suggests the script variables list doesn't get filled with your own variables.