Adding ability to cancel a running PowerShell operation (using System.Management.Automation in VB.NET)

Darren Rose 311 Reputation points
2022-07-20T18:51:30.2+00:00

Hi

I use code such as the (simplified) example below to run a PowerShell command in my VB app using System.Management.Automation.

I need to be able to add the ability to cancel a long running operation once it has started, does the below support the use of CancellationToken or similar, if so how? or if not how can I modify the below so if I click a cancel button on my form it would stop the operation?

Thanks

Private Async Sub btn_Click(sender As Object, e As EventArgs) Handles btn.Click  
  
        Dim computers As New List(Of String)({"PC1", "PC2", "PC3"}) ' this is just example, real code could have hundreds of computers  
  
        Using ps As PowerShell = PowerShell.Create()  
  
            ps.AddCommand("Test-Connection").AddParameter("ComputerName", computers).AddParameter("Count", 1)  
  
            Dim output As New PSDataCollection(Of PSObject)()  
            AddHandler output.DataAdded, AddressOf Output_DataAdded  
  
            AddHandler ps.Streams.Error.DataAdded, AddressOf Error_DataAdded  
  
            Dim results As PSDataCollection(Of PSObject) = Await Task.Run(Function() ps.InvokeAsync(Of PSObject, PSObject)(Nothing, output))  
  
        End Using  
  
    End Sub  
Windows for business Windows Server User experience PowerShell
Developer technologies VB
{count} votes

2 answers

Sort by: Most helpful
  1. Limitless Technology 39,916 Reputation points
    2022-07-21T13:45:06.917+00:00

    Hi there,

    You can add Stop-Process at the end of the script.

    The Stop-Process cmdlet stops one or more running processes. You can specify a process by process name or process ID (PID), or pass a process object to Stop-Process. Stop-Process works only on processes running on the local computer.

    Stop-Process

    https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/stop-process?view=powershell-7.2

    -------------------------------------------------------------------------------------------------------------------------------

    --If the reply is helpful, please Upvote and Accept it as an answer--


  2. Darren Rose 311 Reputation points
    2022-07-30T14:55:57.903+00:00

    The answer on the page below solved my problem

    https://stackoverflow.com/a/38769801/9294915

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.