Execute PowerShell Script from C# with Commandline Arguments
Try creating scriptfile as a separate command:
Command myCommand = new Command(scriptfile);
then you can add parameters with
CommandParameter testParam = new CommandParameter("key","value");myCommand.Parameters.Add(testParam);
and finally
pipeline.Commands.Add(myCommand);
Here is the complete, edited code:
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);runspace.Open();Pipeline pipeline = runspace.CreatePipeline();//Here's how you add a new script with argumentsCommand myCommand = new Command(scriptfile);CommandParameter testParam = new CommandParameter("key","value");myCommand.Parameters.Add(testParam);pipeline.Commands.Add(myCommand);// Execute PowerShell scriptresults = pipeline.Invoke();
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.
ProcessStartInfo startInfo = new ProcessStartInfo();startInfo.FileName = @"powershell.exe";startInfo.Arguments = @"& 'c:\Scripts\test.ps1'";startInfo.RedirectStandardOutput = true;startInfo.RedirectStandardError = true;startInfo.UseShellExecute = false;startInfo.CreateNoWindow = true;Process process = new Process();process.StartInfo = startInfo;process.Start();string output = process.StandardOutput.ReadToEnd();Assert.IsTrue(output.Contains("StringToBeVerifiedInAUnitTest"));string errors = process.StandardError.ReadToEnd();Assert.IsTrue(string.IsNullOrEmpty(errors));
With the contents of the script being:
$someVariable = "StringToBeVerifiedInAUnitTest"$someVariable
I had trouble passing parameters to the Commands.AddScript method.
C:\Foo1.PS1 Hello World HungerC:\Foo2.PS1 Hello WorldscriptFile = "C:\Foo1.PS1"parameters = "parm1 parm2 parm3" ... variable length of params
I Resolved this by passing null
as the name and the param as value into a collection of CommandParameters
Here is my function:
private static void RunPowershellScript(string scriptFile, string scriptParameters){ RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); Pipeline pipeline = runspace.CreatePipeline(); Command scriptCommand = new Command(scriptFile); Collection<CommandParameter> commandParameters = new Collection<CommandParameter>(); foreach (string scriptParameter in scriptParameters.Split(' ')) { CommandParameter commandParm = new CommandParameter(null, scriptParameter); commandParameters.Add(commandParm); scriptCommand.Parameters.Add(commandParm); } pipeline.Commands.Add(scriptCommand); Collection<PSObject> psObjects; psObjects = pipeline.Invoke();}