C#调用PowerShell命令

2011年4月26日 | 分类: 开发 | 标签: , , ,

微软虽然产品众多,但总能找到各种方法来进行整合。最近想用C#调用PowerShell命令,本人测试的环境是Windows 7 x64企业版,自带的PowerShell 2.0,安装Exchange 2007 SP3的管理工具——为了能使用它的EMS命令,Visual Studio 2010。要使用PowerShell命令,需要添加”System.Management.Automation”的引用,如果要使用EMS,还需要在代码中添加Exchange的PSSnapIn,Exchange 2007是”Microsoft.Exchange.Management.PowerShell.Admin”,如果安装的Excahnge 2010的管理工具,则是”Microsoft.Exchange.Management.PowerShell.E2010″,部分主要示例代码如下:

using System;
using System.IO;
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;

namespace HowToRunPowerShell
{
public partial class FormPowerShellSample : Form
{
// Represents the kind of drag drop formats we want to receive
private const string dragDropFormat = “FileDrop”;

public FormPowerShellSample()
{
InitializeComponent();
}

private void buttonRunScript_Click(object sender, EventArgs e)
{
try
{
textBoxOutput.Clear();
textBoxOutput.Text = RunScript(textBoxScript.Text);
}
catch (Exception error)
{
textBoxOutput.Text += String.Format(“\r\nError in script : {0}\r\n”, error.Message);
}
}

/// <summary>
/// Runs the given powershell script and returns the script output.
/// </summary>
/// <param name=”scriptText”>the powershell script text to run</param>
/// <returns>output of the script</returns>
private string RunScript(string scriptText)
{
// create Powershell runspace
RunspaceConfiguration rc = RunspaceConfiguration.Create();
PSSnapInException snapEx = null;
PSSnapInInfo info = rc.AddPSSnapIn(“Microsoft.Exchange.Management.PowerShell.Admin”, out snapEx);
Runspace runspace = RunspaceFactory.CreateRunspace(rc);

// open it
runspace.Open();

// create a pipeline and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();
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
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();
}

#region Drag-drop handling events
private void FormPowerShellSample_DragDrop(object sender, DragEventArgs e)
{
// is it the correct type of data?
if (e.Data.GetDataPresent(dragDropFormat))
{
// dragging files onto the window yields an array of pathnames
string[] files = (string[])e.Data.GetData(dragDropFormat);

if (files.Length > 0)
{
// just read the first file
using (StreamReader sr = new StreamReader(files[0]))
{
// and plunk the contents in the textbox
textBoxScript.Text = sr.ReadToEnd();
}
}
}
}

private void FormPowerShellSample_DragEnter(object sender, DragEventArgs e)
{
// only accept the dropped data if it has the correct format
e.Effect = e.Data.GetDataPresent(dragDropFormat) ? DragDropEffects.Link : DragDropEffects.None;
}
#endregion
}
}

完整代码下载地址: http://www.codeproject.com/KB/cs/HowToRunPowerShell.aspx

Written by Nile Jiang
无猖狂以自彰,当阴沉以自深。

目前还没有任何评论.
注意: 评论者允许使用'@user空格'的方式将自己的评论通知另外评论者。例如, ABC是本文的评论者之一,则使用'@ABC '(不包括单引号)将会自动将您的评论发送给ABC。使用'@all ',将会将评论发送给之前所有其它评论者。请务必注意user必须和评论者名相匹配(大小写一致)。