Did you manage to solve this? I did try using Register-ObjectEvent and get notified if the job dies, but the call to $Service.Stop() in the event action hangs and the service ends up in the “Stopping” state forever…
function OnStart() {
# $Service.Stop()
$serviceJob = Start-Job -ScriptBlock {Start-Sleep -Miliseconds 1000; exit 1}
$jobEvent = Register-ObjectEvent -InputObject $serviceJob -EventName "StateChanged" -Action {
if ($sender.State -ne "Running") {
$Service.Stop()
}
$jobEvent | Unregister-Event
}
}
function OnStop() {
$jobEvent | Unregister-Event
if ($serviceJob.State -eq "Running") {
$serviceJob.Stop()
}
}
$CanStop = $true