1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
using System; using System.Collections.ObjectModel; using System.Management.Automation; // Windows PowerShell namespace. namespace PowerSh { class PowerSh { static void Main(string[] args) { using (PowerShell PowerShellInstance = PowerShell.Create()) { // use "AddScript" to add the contents of a script file to the end of the execution pipeline. // use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline. PowerShellInstance.AddScript("Get-Process | out-file out.txt"); Collection<PSObject> PSOutput = PowerShellInstance.Invoke(); foreach (PSObject outputItem in PSOutput) { // if null object was dumped to the pipeline during the script then a null // object may be present here. check for null to prevent potential NRE. if (outputItem != null) { Console.WriteLine(outputItem.BaseObject.ToString() + "\n"); } } if (PowerShellInstance.Streams.Error.Count > 0) { Console.Write("Error"); } else { Console.Write("Correcto"); } Console.ReadKey(); } } // End Main. } // End PowerSh. } |