Working with .Net 3.5 WPF app. In the app, I'm opening five threads and each thread executes a PowerShell script. Where I'm having trouble is, how do you kill all PowerShell instances that are started?
var threads = new List<Thread>();
for (int i = 0; i <= toProcess; i++)
{
PowerShellWork work = new PowerShellWork();
work.aId = aId;
work.thread = int.Parse(argList[i].iThread);
ThreadStart threadDelegate = new ThreadStart(work.Execute);
Thread newThread = new Thread(threadDelegate);
newThread.Name = associId;
newThread.Start();
Thread.Sleep(1000);
threads.Add(newThread);
}
foreach (var thread in threads)
thread.Join();
class PowerShellWork
{
public string aId;
public int thread;
public void Execute()
{
string shellPath = "powershell.exe";
StringBuilder sb = new StringBuilder();
sb.AppendFormat("\"& '{0}'\" ", @"C:\PS_Scripts\PSupdate.ps1");
sb.AppendFormat(" {0} {1}", aId, thread);
string result = ExecuteCommand(shellPath, sb.ToString());
}
private static string ExecuteCommand(string shellPath, string arguments)
{
arguments = "-noprofile " + arguments;
Process process = new Process();
var info = process.StartInfo;
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = shellPath;
process.StartInfo.Arguments = arguments;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
//process.Kill();
var output = process.StandardOutput;
var error = process.StandardError;
string result = output.ReadToEnd();
process.WaitForExit();
return result;
}
}
Edit* This is how I solved my issue. Please let me know if you know of a better wway.
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
worker.CancelAsync();
ConfigurationManager.AppSettings["StopProcess"] = "Stop";
}
In my PowerShellWork class
process.Start();
do
{
if (ConfigurationManager.AppSettings["StopProcess"] == "Stop")
{
process.Kill();
}
} while (ConfigurationManager.AppSettings["StopProcess"] == "Run" || !process.HasExited);