8

ファイルに保存されている PowerShell スクリプトがあります。Windows PowerShell では、スクリプトを次のように実行します。
.\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));

以下のコードのようなクラスを使用して実行したいのですPipelineが、引数を渡す方法がわかりません (名前付き引数がないことに注意してください。$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();
4

1 に答える 1

18

別の質問へのコメントの1つでそれを見つけました

$args に引数を渡すには、パラメータ名として null を渡します。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();
    }
}
于 2012-04-21T16:18:08.353 に答える