'How can a powershell script detect when task manager has killed it?

I have a powershell script that normal runs as foreground process (i.e. an app, on my desktop in a powerhshell console)

The script is coded such that when ctrl+c is pressed it will go through an orderly shutdown and close.

The script is currently being run as a background process (i.e. no console), but I still need to make it go through an orderly shutdown when it closes. I need to be able to do one of two things....

  1. Modify the script to detect when task manager has killed it and do an orderly shutdown (same as when ctrl+c is used normally), OR
  2. Send the equivalent of a ctrl+c from task manager.


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source