powershell - 如何通过 "killed"或任务管理器在我的进程为 "stop-process"时运行 PowerShell 函数?

标签 powershell

我想编写一个在本地计算机上永久运行的守护程序 PowerShell 脚本。如果它通过停止进程或任务管理器被杀死,我想在它被杀死之前首先到达休息端点。是否可以处理“kill”信号?

[编辑]

感谢 JPBlanc 的建议,我提出了以下建议:

$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;
   }
}

如果我强制终止后台作业创建的进程,我会成功地将“其他进程结束”打印到控制台。但是,如果我终止主进程,我不会得到我想要的 out.txt 文件。我做错了什么吗?

最佳答案

在 Windows 系统上,这并不容易,您必须处理不同的情况:

首先:如果PowerShell进程以自然方式退出,用户退出或脚本退出,甚至右上角的十字,您可以使用PowerShell Engine Events :

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

第二:如果进程被外部进程(任务管理器)终止,我知道的唯一方法是从外部管理您的 PowerShell 进程。您可以使用 WMI 事件或以下方式执行此操作:

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

关于powershell - 如何通过 "killed"或任务管理器在我的进程为 "stop-process"时运行 PowerShell 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33602561/

相关文章:

powershell - 由于超时时间已过错误,此操作返回

powershell - Windows Azure Powershell 'you MUST specify a certificate'

powershell - 在Powershell中打印有用的变量值(特别是涉及$ null/空字符串)

powershell - 如何在powershell脚本中获取命名参数的数量?

azure - 如何使用 Azure Devops 将 powershell 列表变量传输到 terraform?

Powershell 给出 Get-Content : Exception of type 'System.OutOfMemoryException' was thrown

powershell - Powershell:类似Haskell的$(应用)运算符?

Powershell:为什么 (gci c:\ddd).count on an Empty 文件夹不返回 0

javascript - 我正在制作一个 Discord 机器人,需要将一些 Powershell 代码翻译成 Javascript

powershell - powershell远程创建ini文件