使用来自C#的参数调用PowerShell脚本 [英] Invoking PowerShell Script with Arguments from C#

查看:62
本文介绍了使用来自C#的参数调用PowerShell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储在文件中的PowerShell脚本。在Windows PowerShell中,我以

执行脚本。\MergeDocuments.ps1 1.docx 2.docx merge.docx

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"

我想从C#调用脚本。当前,我正在使用Process.Start,如下所示,它可以正常运行:

Process.Start(POWERSHELL_PATH,string.Format(-File \ {0} \ {1 } {2},SCRIPT_PATH,string.Join(,filesToMerge),outputFilename));

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

我想使用 Pipeline 类,类似于下面的代码,但是我不知道如何传递参数(请记住,我没有命名参数,我只是在使用$ args)

I want to run it using Pipeline class, something like the below code but I don't know how to pass the arguments (keep in mind that I don't have named arguments, I am just using $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();


推荐答案

只是在对另一个问题的评论中找到了它

Just found it in one of the comments to another question

为了将参数传递给$ args,请将null用作参数名称,例如 command.Parameters.Add(null, some value);

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

该脚本称为:

.\MergeDocuments.ps1 1.docx 2.docx merge.docx

这里是完整代码:

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();
    }
}

这篇关于使用来自C#的参数调用PowerShell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆