seagull
seagull

Reputation: 217

Run command on script termination/window closure

I use PowerShell in conjunction with Livestreamer (and its new counterpart Streamlink) to stream from various services depending on what is being broadcast. The script I have produced works fine; the only issue is that closing the PowerShell window when I wish to stop viewing the stream often leaves both Livestreamer and my media player running, forcing me to exit both in a specific order (as the script loops otherwise).

A little more information on Livestreamer: It is a tool used to communicate with streaming services as diverse apart as YouTube and Twitch.tv. It captures the output (typically RTMP) and pipes it to a media player instead of forcing the user to rely on web-based technologies. The script I have written is essentially a "wrapper" for Livestreamer that checks an external JSON to ensure the stream is online and then launches Livestreamer. Livestreamer will close once the stream stops, which is caught by the script; the script then loops back to the "online" check and starts from the beginning. This is so the script can be left going; it also means, however, that as soon as the Livestreamer program is closed, the script treats it as the stream going offline and loops back around again. For this reason, I'd like to have the script interfere with the working of Livestreamer as little as physically possible. The man page for Livestreamer itself says it attempts to close media players when the program itself quits, but this functionality is quite unreliable.

The best way for me to fix this would be to trap the closure of the PowerShell console window and execute a command in response. I've investigated PowerShell's trap command but found it wanting in comparison to Unix's (documentation is scant) – I do not believe the following pseudocode has any real-life counterpart:

trap [System.Management.WindowClosed]
     {taskkill /f /im iris.exe; exit}

I fear my task is complicated somewhat by the reliance on 3rd-party programs as opposed to internal PowerShell functions and my desire to trap specifically the "X" button as opposed to CTRL+C.

Upvotes: 1

Views: 909

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174515

Use Register-EngineEvent to register an action to run when the shell exits:

Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action {
    Stop-Process iris -force
}

Upvotes: 3

Related Questions