首页 > Windows开发 > 详细

C#调用PowerShell脚本

时间:2015-11-02 19:26:47      阅读:774      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!