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