Call PowerShell Script with arguments from C #

I have a PowerShell script stored in a file. In Windows PowerShell, I run the script as
.\MergeDocuments.ps1 "1.docx" "2.docx" "merge.docx"

I want to call a script from C #. I am currently using Process.Start as follows, which works just fine:
Process.Start(POWERSHELL_PATH, string.Format("-File \"{0}\" {1} {2}", SCRIPT_PATH, string.Join(" ", filesToMerge), outputFilename));

I want to run it using the Pipeline class, something like the code below, but I don’t know how to pass the arguments (keep in mind that I have no named arguments, I just use $ args)

 // create Powershell runspace Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace); runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); // create a pipeline and feed it the script text (AddScript method) or use the filePath (Add method) Pipeline pipeline = runspace.CreatePipeline(); Command command = new Command(SCRIPT_PATH); command.Parameters.Add("", ""); // I don't have named paremeters pipeline.Commands.Add(command); pipeline.Invoke(); runspace.Close(); 
+6
source share
1 answer

Just found it in one of the comments on another question

To pass arguments to $ args null as the parameter name, for example. command.Parameters.Add(null, "some value");

The script is called:
.\MergeDocuments.ps1 "1.docx" "2.docx" "merge.docx"

Here is the complete code:

 class OpenXmlPowerTools { static string SCRIPT_PATH = @"..\MergeDocuments.ps1"; public static void UsingPowerShell(string[] filesToMerge, string outputFilename) { // create Powershell runspace Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace); runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); // create a pipeline and feed it the script text Pipeline pipeline = runspace.CreatePipeline(); Command command = new Command(SCRIPT_PATH); foreach (var file in filesToMerge) { command.Parameters.Add(null, file); } command.Parameters.Add(null, outputFilename); pipeline.Commands.Add(command); pipeline.Invoke(); runspace.Close(); } } 
+14
source

Source: https://habr.com/ru/post/913797/


All Articles