父进程结束时杀死子进程

kill child processes when parent ends

我的目标是杀死(或以某种方式优雅地关闭)由 powershell 脚本启动的子进程,这样在父进程死后(通常通过点击脚本末尾或通过崩溃或 ctrl+c 或任何其他方式)。

我尝试了几种方法,但 none 按预期工作:

# only one line was active at time, all other were commented
start-job -scriptblock { & 'notepad.exe' }    # notepad.exe started, script continues to end, notepad.exe keep running
start-job -scriptblock { 'notepad.exe' }      # notepad.exe not started, script continues to end
notepad.exe                                   # notepad.exe started, script continues to end, notepad.exe keep running
& notepad.exe                                 # notepad.exe started, script continues to end, notepad.exe keep running
start-Process -passthru -FilePath notepad.exe # notepad.exe started, script continues to end, notepad.exe keep running

# give script some time before ending
Write-Host "Begin of sleep section"
Start-Sleep -Seconds 5
Write-Host "End of sleep section"

你可以用finally clause这种东西。 finally 子句在 try 块之后执行,即使 try 块的执行抛出异常或者执行被用户中止。

因此,解决您的问题的一种方法如下:

  1. 跟踪子进程的进程 ID,您的脚本正在生成并且

  2. 在 finally 子句中终止这些进程。

    try
    {
       $process = Start-Process 'notepad.exe' -PassThru 

       # give script some time before ending
        Write-Host "Begin of sleep section"
        Start-Sleep -Seconds 5
        Write-Host "End of sleep section"

    }
    finally
    {
        # Kill the process if it still exists after the script ends.
        # This throws an exception, if process ended before the script.
        Stop-Process -Id $process.Id
    }