Invoking PowerShell Script with Arguments from C#

后端 未结 1 1943
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-06 08:06

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

相关标签:
1条回答
  • 2020-12-06 08:16

    Just found it in one of the comments to another question

    In order to pass arguments to the $args pass null as the parameter name, e.g. command.Parameters.Add(null, "some value");

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

    Here is the full 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();
        }
    }
    0 讨论(0)
提交回复
热议问题