gpt4 book ai didi

powershell - 在脚本终止/窗口关闭时运行命令

转载 作者:行者123 更新时间:2023-12-03 01:09:49 27 4
gpt4 key购买 nike

我将PowerShell与Livestreamer(及其新的对等产品Streamlink)结合使用,根据广播的内容从各种服务中进行流式传输。我制作的脚本效果很好;唯一的问题是,当我希望停止查看流时,关闭PowerShell窗口通常会使Livestreamer和我的媒体播放器同时运行,从而迫使我以特定顺序退出两者(否则脚本会循环播放)。

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.



解决此问题的最佳方法是捕获PowerShell控制台窗口的关闭并执行命令以作为响应。我研究了PowerShell的 trap命令,但发现它与Unix(文档很少)相比是想要的-我不认为以下伪代码具有任何现实的对应物:
trap [System.Management.WindowClosed]
{taskkill /f /im iris.exe; exit}

我担心我的任务会由于与第三方PowerShell相对而不是内部PowerShell函数的依赖而变得有些复杂,并且我希望专门捕获“X”按钮而不是CTRL + C。

最佳答案

使用 Register-EngineEvent 注册要在 shell 程序退出时运行的操作:

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

关于powershell - 在脚本终止/窗口关闭时运行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41201878/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com