1

I have an application that allows chains of tasks to be defined and scheduled. These tasks are pre-defined c# classes that are run in combination with user defined configuration (think WWF or Logic Apps but very domain specific).

The tasks don't always cover everything that needs to be accomplished so I've added in the ability to run custom powershell scripts in an c# runspace. In the edge cases where to included tasks don't work the user can use the powershell task to run any custom actions they need to.

This has worked great but I'm running into issues where the custom Powershell scripts are creating new processes that never get closed out. I use cancellation tokens to allow the scripts to be aborted but this only closes the runspace not processes created by it. What are my options to ensure any processes that may be created by the custom powershell scripts are cleaned up on exit of the script/runspace?

The only two options I could think of were:

  • Write the script to temp file and run in new c# process using powershell.exe. Track new process ID and then kill and processes afterwards that have a parent ID of the script process.
  • Run the c# runspace in a separate process by dynamically creating a new EXE for the c# powershell wrapper code. Track new process ID and then kill and processes afterwards that have a parent ID of the script process.

Both of the feel clunky and ruin easily being able to pass information/objects between C# and the powershell environment. I'm currently injecting a lot of context info into the powershell runspace to be used in the user defined script.

playsted
  • 490
  • 3
  • 10
  • [Looks to be very related](https://stackoverflow.com/q/7189117/3905079). Does this look like it would solve your issue? – briantist Jul 07 '17 at 23:01
  • The suggestions in that link are what I was considering for those two options I listed. The issue with the current setup is that many workflows run under the same parent process so I can't differentiate which processes to kill for a specific canceled powershell script. – playsted Jul 07 '17 at 23:49
  • Oh yeah that makes sense. – briantist Jul 07 '17 at 23:50
  • Did you resolve this? I have a scenario where I want the processes spawned by the runspace to be killed if my app's process is killed i.e not a graceful shutdown. Any ideas? – rukiman Sep 14 '20 at 08:46
  • @rukiman went with a setup based on the first option above but it's overly complicated as you have to monitor WMI events for processes that are created and build up a process tree. When the powershell process exists walk the tree and make sure all processes exited. – playsted Oct 21 '20 at 14:02

0 Answers0