//origion from https://gist.github.com/SQLJana/1738dff1b151e2412240067167076e7a
using System;
using System.Diagnostics;
using System.Collections.ObjectModel; //Used for CollectionSystem.Collections.ObjectModel.Collection
using System.ComponentModel;
using System.Data;
using System.Management.Automation.Runspaces;
using System.Management.Automation;
using System.Text;
namespace WindowsEventLab
{
public enum ResultType
{
PSObjectCollection = 0,
DataTable = 1
}
public class PowerShellHelper
{
public PowerShellHelper()
{
}
//This works but only returns standard output as text and not an object but will still work to invoke full-fledged scripts
//Object invokedResults = PowerShellHelper.InvokePowerShellScript(@"C:\MyDir\TestPoShScript.ps1");
public static Object InvokePowerShellScript(string scriptPath)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
Process process = new Process();
Object returnValue = null;
startInfo.FileName = @"powershell.exe";
startInfo.Arguments = (@"& 'PATH'").Replace("PATH", scriptPath);
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
process = new Process { StartInfo = startInfo, EnableRaisingEvents = true };
process.StartInfo.StandardOutputEncoding = Encoding.UTF8;
process.StartInfo.StandardErrorEncoding = Encoding.UTF8;
process.OutputDataReceived += new DataReceivedEventHandler
(
delegate (object sender, DataReceivedEventArgs e)
{
//For some e.Data always has an empty string
returnValue = e.Data;
//using (StreamReader output = process.StandardOutput)
//{
// standardOutput = output.ReadToEnd();
//}
}
);
process.Start();
//process.BeginOutputReadLine(); //This is starts reading the return value by invoking OutputDataReceived event handler
process.WaitForExit();
Object standardOutput = process.StandardOutput.ReadToEnd();
//Assert.IsTrue(output.Contains("StringToBeVerifiedInAUnitTest"));
String errors = process.StandardError.ReadToEnd();
//Assert.IsTrue(string.IsNullOrEmpty(errors));
process.Close();
//For some reason returnValue does not have the object type output
//return returnValue;
return standardOutput;
}
//IDictionary parameters = new Dictionary();
//parameters.AddUser("Identity", "My-AD-Group-Name");
//Collection
這時候你會遇到 using System.Management.Automation; 系統竟然不認識,這時候我網路上找到保哥這篇文章