How to get task scheduler to kill child process launched from a powershell script

Question:

I have a powershell script that launches an exe process. I have a task scheduled to run this powershell script on computer idle, and I have it set to stop it when it’s not idle.

The problem is task schedule doesn’t kill the launched exe process, I’m assuming it’s just trying to kill the powershell process.

I can’t seem to find a way to make the launched exe as a subprocess of a powershell.exe when it’s launched from task scheduler

I’ve tried launching the process with invoke-expression, start-proces, I’ve also tried to pipe to out-null, wait-process, etc.. nothing seems to work when ps1 is launched from task scheduler.

Is there a way to accomplish this?

Thanks

Answer:

I don’t think there is an easy solution for your problem since when a process is terminated it doesn’t receive any notifications and you don’t get the chance to do any cleanup.

But you can spawn another watchdog process that watches your first process and does the cleanup for you:

The launch script waits after it has nothing else to do:

The watchdog script kills the child if the launch script got terminated:

This is maybe a bit complicated and depending on your situation can be simplified. Anyways, I think you get the idea.

Source:

How to get task scheduler to kill child process launched from a powershell script by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply