C#调用PowerShell执行脚本方法

/*

* C#调用PowerShell代码示例 

*

* 需要引用System.Management.Automantion.dll

*/

using System;

using System.Collections.Generic;

using System.Collections.ObjectModel;

using System.Management.Automation;

using System.Management.Automation.Runspaces;

using System.Text;

namespace ConsoleApplication

{

    class Program

    {

        static void Main(string[] args)

        {

            string result = RunScript("get-process");

            

            Console.Write(result);

            Console.Read();

        }

       

        /// <summary>

        /// 运行脚本信息,返回脚本输出

        /// </summary>

        /// <param name="scriptText">需要运行的脚本</param>

        /// <returns>output of the script</returns>

        private static string RunScript(string scriptText)

        {

            // create Powershell runspace

            Runspace runspace = RunspaceFactory.CreateRunspace();

            // 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 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();

        }

    }

}

posted @ 2009-03-12 14:57  Yoshow  阅读(4667)  评论(0编辑  收藏  举报