Suppose you have a process that spawns a tree of subprocesses - I am trying to create a watchdog process to kill the entire process tree in the event that the head of the tree is aborted (head refers to the caller of these two lines)
Start-Process -FilePath '..\SpawnProcessTree.bat' -PassThru
Start-Process powershell -ArgumentList '..\WatchDogKillProcessTree.ps1', $pid -Wait
The above code segment works flawlessly in the event of an abortion of the entire script, but will hang indefinitely if the script is not aborted.
The code in WatchDogKillProcessTree.ps1 looks like:
$waitproc = Get-Process -Id $ps_pid
$waitproc.WaitForExit()
Kill-Tree $ps_pid
Where Kill-Tree is taken from Terminate process tree in PowerShell given a process ID
The obvious answer would be to swap the lines around:
$watchdog = Start-Process powershell -ArgumentList '..\WatchDogKillProcessTree.ps1', $pid -PassThru
Start-Process -FilePath '..\SpawnProcessTree.bat' -Wait
$watchdog.Kill()
Following this https://superuser.com/questions/1302681/powershell-finally-block-not-executed-in-windows-task-scheduler
But when I do this, the watchdog does not kill the process tree on abortion. Would anybody happen to have an idea why reordering these lines does not work as intended? Please let me know if any additional information is required.