[英]How to call powershell script with configfile,parameters in c#
[英]How could call powershell script in c# with parameters
我試圖用c#中的參數調用powershell腳本。 是否有任何選項只提供powershell腳本文件和參數,而不是將整個powershell命令作為c#代碼中的字符串。
快速谷歌搜索真的為您提供所需的一切。 這個來自http://www.devx.com/tips/Tip/42716
您將需要Reference System.Management.Automation
然后使用
using System.Management.Automation;
using System.Management.Automation.Runspaces;
創建一個運行空間來托管PowerScript環境:
Runspace runSpace = RunspaceFactory.CreateRunspace();
runSpace.Open();
使用運行空間,為cmdlet創建一個新管道:
Pipeline pipeline = runSpace.CreatePipeline();
創建Command對象以表示要執行的cmdlet,並將它們添加到管道中。 此示例檢索所有進程,然后按內存使用情況對其進行排序。
Command getProcess = new Command("Get-Process");
Command sort = new Command("Sort-Object");
sort.Parameters.Add("Property", "VM");
pipeline.Commands.Add(getProcess);
pipeline.Commands.Add(sort);
上述代碼的功能與以下PowerShell命令行相同:
PS > Get-Process | Sort-Object -Property VM
最后,執行管道中的命令並對輸出執行以下操作:
Collection output = pipeline.Invoke();
foreach (PSObject psObject in output)
{
Process process = (Process)psObject.BaseObject;
Console.WriteLine("Process name: " + process.ProcessName);
}
我最后做了一件事
public static string RunScript(string scriptText)
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
pipeline.Commands.Add("Out-String");
try
{
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
StringBuilder stringBuilder = new StringBuilder();
if (pipeline.Error.Count > 0)
{
//iterate over Error PipeLine until end
while (!pipeline.Error.EndOfPipeline)
{
//read one PSObject off the pipeline
var value = pipeline.Error.Read() as PSObject;
if (value != null)
{
//get the ErrorRecord
var r = value.BaseObject as ErrorRecord;
if (r != null)
{
//build whatever kind of message your want
stringBuilder.AppendLine(r.InvocationInfo.MyCommand.Name + " : " + r.Exception.Message);
stringBuilder.AppendLine(r.InvocationInfo.PositionMessage);
stringBuilder.AppendLine(string.Format("+ CategoryInfo: {0}", r.CategoryInfo));
stringBuilder.AppendLine(
string.Format("+ FullyQualifiedErrorId: {0}", r.FullyQualifiedErrorId));
}
}
}
}
else
stringBuilder.AppendLine(string.Format("Build is Success"));
return stringBuilder.ToString();
}
catch (Exception ex)
{
string err = ex.ToString();
err = "Build Failed!!!" + "\r\n" + "Check the Setup File Available or Path error";
return err;
}
}
SCRIPT = "buildmsi.ps1 " + ssource + " " + sdestination;
projectbuildstatus.Text = RunScript(SCRIPT);
感謝Ale Tiro的想法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.