如何在C#中停止powershell调用程序

时间:2014-08-21 10:00:58

标签: c# powershell

我用C#调用powershell命令,并调用powershell命令后台。我想终止后台线程。每次,我终止后台线程,powershell仍在运行,导致我无法再次运行该线程。是否有任何方法可以终止PowerShell执行?

后台主题如下:

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. 
} })

2 个答案:

答案 0 :(得分:2)

由于PowerShell类上的Stop()方法,停止PowerShell脚本非常简单。

如果要异步调用脚本,可以很容易地使用CancellationToken

using(cancellationToken.Register(() => powershell.Stop())
{
    await Task.Run(() => powershell.Invoke(powershellCommand), cancellationToken);
}

答案 1 :(得分:1)

我知道我迟到了,但我刚刚写了一个扩展方法,它将对BeginInvoke()EndInvoke()的调用粘合到任务并行库(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);
}