![]() |
#2
yms1232013-04-20 10:08
/*
* C#调用PowerShell代码示例 * * 需要引用System.Management.Automantion.dll */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Text; namespace ConsoleApplication { class Program { static void Main(string[] args) { string result = RunScript("get-process"); Console.Write(result); Console.Read(); } /// <summary> /// 运行脚本信息,返回脚本输出 /// </summary> /// <param name="scriptText">需要运行的脚本</param> /// <returns>output of the script</returns> private static string RunScript(string scriptText) { // create Powershell runspace Runspace runspace = RunspaceFactory.CreateRunspace(); // open it runspace.Open(); // create a pipeline and feed it the script text Pipeline pipeline = runspace.CreatePipeline(); (scriptText); // add an extra command to transform the script output objects into nicely formatted strings // remove this line to get the actual objects that the script returns. For example, the script // "Get-Process" returns a collection of System.Diagnostics.Process instances. ("Out-String"); // execute the script Collection results = pipeline.Invoke(); // close the runspace runspace.Close(); // convert the script result into a single string StringBuilder stringBuilder = new StringBuilder(); foreach (PSObject obj in results) { stringBuilder.AppendLine(obj.ToString()); } return stringBuilder.ToString(); } } } 如果说ps1文件内部是类似于cmd的文本文件一种,可以尝试用修改文本文件的方法来修改ps1文件的内容 |
C#调用.ps1
用写程序调用.ps1,不仅仅只是执行.ps1文件,还需要改掉.ps1中的内容
再执行.ps1这个文件