我正在尝试使用来自 c# 的参数调用 powershell 脚本。是否有任何选项可以仅提供 powershell 脚本文件以及参数,而不是在 c# 代码中将整个 powershell 命令作为字符串提供。
问问题
9187 次
2 回答
8
快速的谷歌搜索确实可以满足您的所有需求。这个来自http://www.devx.com/tips/Tip/42716
你需要参考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);
}
于 2013-04-02T11:49:18.077 回答
1
我最后做了这样的事情
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 的想法
于 2013-04-03T17:40:40.947 回答