title: PowerShell watchdog to kill process tree
body: <p>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)</p>
  
  <pre><code>Start-Process -FilePath '..\SpawnProcessTree.bat' -PassThru
  Start-Process powershell -ArgumentList '..\WatchDogKillProcessTree.ps1', $pid -Wait
  </code></pre>
  
  <p>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.  </p>
  
  <p>The code in WatchDogKillProcessTree.ps1 looks like:</p>
  
  <pre><code>$waitproc = Get-Process -Id $ps_pid
  $waitproc.WaitForExit()
  Kill-Tree $ps_pid
  </code></pre>
  
  <p>Where Kill-Tree is taken from <a href="https://stackoverflow.com/questions/55896492/terminate-process-tree-in-powershell-given-a-process-id">Terminate process tree in PowerShell given a process ID</a></p>
  
  <p>The obvious answer would be to swap the lines around:</p>
  
  <pre><code>$watchdog = Start-Process powershell -ArgumentList '..\WatchDogKillProcessTree.ps1', $pid -PassThru
  Start-Process -FilePath '..\SpawnProcessTree.bat' -Wait
  $watchdog.Kill()
  </code></pre>
  
  <p>Following this <a href="https://superuser.com/questions/1302681/powershell-finally-block-not-executed-in-windows-task-scheduler">https://superuser.com/questions/1302681/powershell-finally-block-not-executed-in-windows-task-scheduler</a></p>
  
  <p>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. </p>