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.