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

fro*_*ake 4 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. 
} })
Run Code Online (Sandbox Code Playgroud)

AHo*_*ego 6

我知道我迟到了,但我刚刚编写了一个扩展方法,它将调用粘合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);
}
Run Code Online (Sandbox Code Playgroud)

  • 我知道这篇文章是 6 年前发布的,但我花了很长时间试图找到一种方法来处理取消 VB.NET 应用程序中长时间运行的 PowerShell 命令,并且在各个论坛上没有得到对我的问题的任何答复,我终于偶然发现了您的扩展方法在这里回答,它解决了我的问题并且工作得很好 - 所以只想说谢谢!!!! (2认同)

Pau*_*ner 5

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

CancellationToken如果您想异步调用脚本,可以轻松使用 a 进行连接:

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