xdhmoore
xdhmoore

Reputation: 9915

How do I run a PowerShell function upon my process being "killed" via "stop-process" or the task manager?

I want to write a daemon PowerShell script that runs forever on a local machine. If it is killed via stop-process or the task manager, I want to first hit a rest endpoint before it is killed. Is it possible to handle a "kill" signal?

[EDIT]

Thanks to JPBlanc's suggestion, I have come up with the following:

$thisproc = get-process -name powershell
$other = start-job -scriptblock {
   while($true) {
      wait-process $thisproc -timeout 10
      if ($thisproc.HasExited) {
         echo "this process stopped" > out.txt
         exit;
      }
   }
}

while ($true) {
   wait-job $other -timeout 10
   if ($other.state -eq 'Stopped' -Or $other.state -eq 'Failed') {
      echo "other process ended"
      exit;
   }
}

If I force kill the process the background job creates, I successfully get "other process ended" printed to the console. However, if I kill the main process, I don't get an out.txt file as I am aiming for. Am I doing something wrong?

Upvotes: 2

Views: 2088

Answers (1)

JPBlanc
JPBlanc

Reputation: 72680

On Windows System it's not so easy you have to handle different cases :

First : if the PowerShell Process exit in a natural way, user exit or script exit or even the cross on the right corner you can use PowerShell Engine Events :

$a = [System.Management.Automation.PSEngineEvent]::Exiting
Register-EngineEvent -SourceIdentifier $a -Action {[console]::Beep(500,500)}

Second : if the process is killed by an external process (Task Manager) the only way I know is to manage your PowerShell Process from outside. You can do so using WMI events or this :

$a = get-process PowerShell
$a.waitforexit()
"PowerShell has stopped running."

Upvotes: 2

Related Questions