Fork me on GitHub
C# 调用PowerShell方法

C# 调用PowerShell方法

PowerShell应为编写和运行都很方便,所以为了重复利用,经常写了一些小方法或者PS代码片段。使用的时候可能会很难找到自己想要的那个方法,如果要是有一个界面把这些代码管理起来并且调用,那就很爽了

1.创建一个powershell的方法,供C#调用,方法很简单,两个数的加法运算

function Sum

{

param([int]$first, [int]$second)

 

$result = $first + $second

 

return $result

}

 

 2. 在C#的控制台程序中创建一个私有方法,调用powershell

首先定义一个powershell存放路径的全局变量

private static string script =File.ReadAllText(@"Path\Sum.ps1");

        private static void CallPS1()

        {

            using (Runspace runspace = RunspaceFactory.CreateRunspace())

            {

                runspace.Open();

                PowerShell ps = PowerShell.Create();

                ps.Runspace = runspace;

                ps.AddScript(script);

                ps.Invoke();

 

                ps.AddCommand("Sum").AddParameters(

                    new Dictionary<string, int>()

                    {

                        {"first", 5},

                        {"second", 4}

                    }

                    );

                foreach (PSObject result in ps.Invoke())

                {

                    Console.WriteLine("CallPS1()");

                    Console.WriteLine(result);

                }

            }

        }

调用方法需要添加一个引用System.Management.Automation.dll 
如果找不到可以到这个路径下找到:C:\windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll

 
 
 
posted on 2013-06-13 09:33  HackerVirus  阅读(318)  评论(0编辑  收藏  举报