C# 和 PowerShell都是基于.net 平台面向对象的语言,由于PowerShell脚本功能强大,对于复制删除文件,管理进程和服务,读取EventLog,操作注册表等任务,PowerShell做起来很容易,我们可以将这些内容封装在PowerShell脚本中,C#代码仅做工作流的事情,这样发挥了脚本高效性的优势,脚本重用性强(可以使用Invoke运行在远程服务器上),而且修改简单。所以,使用C# 和脚本结合的方式是一种理想的组合。
下面介绍一个简单的例子,说明C# 如何调用PowerShell脚本。
private static string GetFileContent(string filePath)
{
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader reader = new StreamReader(fs);
return reader.ReadToEnd();
}
private static string RunScript(string filePath)
{
// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();
// create a pipeline and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();
string scriptText = GetFileContent(filePath);
pipeline.Commands.AddScript(scriptText);
// add an extra command to transform the script output objects into nicely formatted strings
// remove this line to get the actual objects that the script returns. For example, the script
// "Get-Process" returns a collection of System.Diagnostics.Process instances.
//pipeline.Commands.Add("Out-String");
// execute the script
System.Collections.ObjectModel.Collection<PSObject> results = pipeline.Invoke();
// close the runspace
runspace.Close();
// convert the script result into a single string
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder.ToString();
}
static void Main(string[] args)
{
string filePath = "1.ps1";
RunScript(filePath);
Console.ReadKey();
}
不仅如此,可以通过C# 给脚本传参数,下一篇会介绍。