Asaf Shazar
Asaf Shazar

Reputation: 1065

Perform some event on "Stop Operation

I am looking to perform some function that take action on Stoping the Script

By clicking the enter image description here

Is that possible??

I am using .Net object and some of them must do Dispose to close them. I want to know if there possible to do that?

Upvotes: 0

Views: 472

Answers (1)

zdan
zdan

Reputation: 29470

If I understand your question, you want to know if you can somehow trap the pressing of the Stop button (receipt of break signal). I don't know of a way, in powershell, to notice the break signal, but you can use a finally block to make sure that your Dispose code gets called. Here's my simple test:

try{
    while($true)
    {
        Write-Host "In try block . . . "
        Start-Sleep 1
    }
}
catch
{
       Write-Host "In catch block"
}
finally
{
       Write-Host "In finally block"
}

When I run it from the ISE and press the stop button (or press ctrl-C) I get:

# C:\Temp> .\stopEx.ps1
In try block . . . 
In try block . . . 
In finally block

Upvotes: 2

Related Questions