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:
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.
} })
I know I'm late to the party but I've just written an extension method which glues up the calls to BeginInvoke() and EndInvoke() into Task Parallel Library (TPL):
public static Task<PSDataCollection<PSObject>> InvokeAsync(this PowerShell ps, CancellationToken cancel)
{
return Task.Factory.StartNew(() =>
{
// Do the invocation
var invocation = ps.BeginInvoke();
WaitHandle.WaitAny(new[] { invocation.AsyncWaitHandle, cancel.WaitHandle });
if (cancel.IsCancellationRequested)
{
ps.Stop();
}
cancel.ThrowIfCancellationRequested();
return ps.EndInvoke(invocation);
}, cancel);
}
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:
using(cancellationToken.Register(() => powershell.Stop())
{
await Task.Run(() => powershell.Invoke(powershellCommand), cancellationToken);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With