Reputation: 6074
I'm writing a powershell script, that must start some background processes in order to automate a testing process.
# Start Server
$server=Start-Process -FilePath "server" -PassThru
# Does some testing
# Eventually exit 1 will be called
# Stop Server
Stop-Process -Id $server.Id
In case an abnormal exit occured during my testing process I'm not able to stop all started processes with my script an I'm left with some dangling processes. How can I automatically kill all started processes of my script in case the script is exited?
Upvotes: 1
Views: 367
Reputation: 13141
You could store all started processes information in an array. Then use trap which will run all your cleanup statements when terminating error occurs.
$proclist = @()
$proclist += Start-Process -FilePath "server" -PassThru
# testing
trap {
foreach ($proc in $proclist) {
Stop-Process -Id $proc.Id -Force -ErrorAction continue -Verbose
}
}
Upvotes: 2