1

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?

1 Answer 1

2

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
 }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the fast reply. I was not aware of trap.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.