Peter
Peter

Reputation: 3

Exit powershell script when another process ends

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?

Upvotes: 0

Views: 746

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174845

Use Environment.Exit():

Register-ObjectEvent $gameRunning -EventName Exited -Action {[Environment]::Exit(0)} -SourceIdentifier NotepadExited

Upvotes: 1

Related Questions