码迷,mamicode.com
首页 > Windows程序 > 详细

C#调用PowerShell脚本

时间:2015-11-02 19:27:26      阅读:539      评论:0      收藏:0      [点我收藏+]

标签:

今天通过一个小例子,学习了C#如何调用PowerShell脚本文件的Function以及传参。

       private bool CallPowershell(string outputFile)
        {
            string ddcHost = "test";
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
            runspace.Open();

            bool result = false;
            try
            {
                PowerShell ps = PowerShell.Create();
                ps.Runspace = runspace;
                ps.AddScript("param($paramList)");
                ps.AddArgument(m_paramList);
                ps.AddScript(string.Format("Import-Module -Name {0}", "testPath"));
                ps.AddScript(string.Format("Get-MachineList {0} {1} $paramList", ddcHost, outputFile));

                ps.Invoke();
                if (File.Exists(outputFile))
                {
                    result = true;
                }
            }
            catch (System.Exception ex)
            {
                Trace.WriteLine("[Error] Failed to execute command, {0}", ex.Message);
            }
            runspace.Close();
            runspace.Dispose();

            return result;
        }

 

C#调用PowerShell脚本

标签:

原文地址:http://www.cnblogs.com/summer1987/p/4930943.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!