0

I am trying to make a powershell script to exit simultaneously with notepad. The script should do file backups in the background, so it runs with while(1). I subscribe to exited event of notepad process, but exit command doesn't seem to work in Action block. Nothing happens when I close notepad.

$gameRunning = Get-Process notepad -ErrorAction SilentlyContinue

if ($gameRunning) {
Register-ObjectEvent -InputObject ($gameRunning) -EventName exited -Action {exit} -SourceIdentifier NotepadRunning
}
else {
Write-Host "Game not running."
}

while(1)
{}

Any idea how to make it exit from Action scope?

3
  • Well, it blocks the process, and I need it to do file backups in the background. Commented Feb 1, 2018 at 22:50
  • Then you better to check $gameRunning.HasExited in safe to interrupt points. Otherwise you are risking to interrupt your background backup in undetermined state. Commented Feb 2, 2018 at 0:45
  • Thank you, fair point, I will give it a thought too. Commented Feb 2, 2018 at 7:56

1 Answer 1

1

Use Environment.Exit():

Register-ObjectEvent $gameRunning -EventName Exited -Action {[Environment]::Exit(0)} -SourceIdentifier NotepadExited
Sign up to request clarification or add additional context in comments.

Comments

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.