使用 .Net 3.5 WPF应用。在应用程序中,我打开五个线程,每个线程执行一个PowerShell脚本。我遇到问题的地方是,你如何杀死所有启动的PowerShell实例?
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;
}
}
编辑* 这就是我解决问题的方法。如果你知道更好的w w,请告诉我。
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
worker.CancelAsync();
ConfigurationManager.AppSettings["StopProcess"] = "Stop";
}
在我的PowerShellWork类中
process.Start();
do
{
if (ConfigurationManager.AppSettings["StopProcess"] == "Stop")
{
process.Kill();
}
} while (ConfigurationManager.AppSettings["StopProcess"] == "Run" || !process.HasExited);