在.Net窗体中运行PowerShell命令

PowerShell 1.0是微软早在2006年就推出的强大的Windows命令行外壳程序,它类似于在Unix/Linux下的shell外壳,但却比其更加强大,因为PowerShell的命令可以直接存取对象!PowerShell现在随同SQL Server 2008一起被安装,所以逐渐被大家了解和熟悉。PowerShell必须运行在.Net平台之上,而且其逐渐的成为了.Net平台的对象脚本语言。在这里,我们创建一个.Net程序示例,通过调用Windows PowerShell命名空间下的对象来执行命令脚本,效果就像在PowerShell下执行命令一样。

我们的版本

为了使.Net程序能够执行PowerShell脚本,必须在程序中对支持Windows PowerShell的命名空间System.Management.Automation加以引用,程序集路径为C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0。更多关于PowerShell SDK信息请参考MSDN。

我们所用到其实就是两个关键类,Runspace和Pipeline。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
​
private string RunScript(string scriptText)
{
    // 创建 Powershell runspace
    Runspace runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    // 创建一个 pipeline,并添加命令脚本
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(scriptText);
    // 格式化输出命令执行结果
    pipeline.Commands.Add("Out-String");
    // 执行脚本
    Collection<PSObject> results = pipeline.Invoke();
    runspace.Close();
    // 将执行结果输出到StringBuilder
    StringBuilder stringBuilder = new StringBuilder();
    foreach (PSObject obj in results)
    {
        stringBuilder.AppendLine(obj.ToString());
    }
    return stringBuilder.ToString();
}
​
private void button1_Click(object sender, EventArgs e)
{
    try
    {
        textBox2.Clear();
        textBox2.Text = RunScript(textBox1.Text);
    }
    catch (Exception error)
    {
        textBox2.Text += String.Format("\r\n脚本执行错误:{0}\r\n", error.Message);
    }
}

该示例程序在Windows XP SP3 + Visual Studio 2008 SP1 + PowerShell 1.0 下编译调试通过。

在.Net窗体中运行PowerShell命令

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

滚动到顶部