[英]Invoking PowerShell Script with Arguments from C#
我有一個存儲在文件中的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();
剛剛在另一個問題的評論中找到了它
為了將參數傳遞給$ 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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.