Question:
I’m invoking powershell command with C#, and powershell command is invoked background. and i want to terminate the background thread. everytime, i terminate the background thread, the powershell is still running which result in that i can’t run that thread again. is there any method to terminate powershell execution?
the background thread as follows:
1 2 3 4 5 6 7 8 9 10 |
Task.run(()=>{ while(...) {... if (cancellationToken.IsCancellationRequested) { cancellationToken.ThrowIfCancellationRequested(); }}}); Task.run(()=>{ while(...) { powershell.invoke(powershellCommand);// it will execute here, I don't know how to stop. } }) |
Answer:
Stopping a PowerShell script is pretty simple thanks to the Stop()
method on the PowerShell class.
It can be easily hooked into using a CancellationToken
if you want to invoke the script asynchronously:
1 2 3 4 5 |
using(cancellationToken.Register(() => powershell.Stop()) { await Task.Run(() => powershell.Invoke(powershellCommand), cancellationToken); } |