C#调用PowerShell脚本

今天通过一个小例子,学习了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;
        }

 

posted @ 2015-11-02 18:08  乡下小土妞  阅读(2509)  评论(0编辑  收藏  举报