Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stop powershell invoker in C#

Tags:

c#

powershell

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. 
} })
like image 270
frostcake Avatar asked Oct 27 '25 09:10

frostcake


2 Answers

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);
}
like image 60
AHowgego Avatar answered Oct 30 '25 00:10

AHowgego


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);
}
like image 44
Paul Turner Avatar answered Oct 29 '25 22:10

Paul Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!