Ok, now that we have unique processes and such it gets a little easier, I got two different excel processes running and then used Get-Process & MainWindowTitle to distinguish between them, I then got a 3rd instance running use your ComObject command so now we have this:
get-process excel | select MainWindowTitle, Id, StartTime | Sort StartTime
MainWindowTitle Id StartTime
Book1 - Excel 2948 2/26/2018 7:37:03 PM
Book2 - Excel 16904 2/26/2018 7:37:23 PM
14024 2/26/2018 8:34:42 PM
(note: there is no MainWindowTitle for the ComObject in my test)
Without knowing everything you are doing, you should be able to launch an instance of Excel, get all Excel PIDs & sort by the StartTime so the last or first (if using Desc) PID is the newest process so it should be the one you want to end once whatever you are doing is done.
Something like this:
((get-process excel | select MainWindowTitle, ID, StartTime | Sort StartTime)[-1]).Id
PS C:> 14024
Make sure you create a variable for each instance you are creating to keep things easier, possibly $E_FunctionName so at the end it is just a simple:
Stop-Process -Id 14024
Stop-Process -Id $E_FunctionName
Depending on how long things run etc, you could get the PID of any running instance at the beginning of the script (i.e. these should be your non script instances) so you can exclude those from any commands to end processes, likewise you could add the script related PIDs to a variable and track what PIDs the script has launched so at the very end you can ensure none of those PIDs are still active.
$PIDs = @(14024, 2000, 18064,2948)
Get-Process -Id $PIDs -ErrorAction SilentlyContinue
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
1241 107 120324 109864 19.33 2948 1 EXCEL
Am I getting close to what you need?