How to stop a PS Service that has OnStart errors

In the service I am creating, I do certain validations at the beginning of OnStart function. Whenever there is an error in the validation, I need to abort the service start. I tried everything, but the service always starts, although not properly initialized because of the error.

I tried

 if ( such error ) { throw 'there was an error' }


 if ( such error ) { throw 'there was an error'; exit 13678} 

besides the above code, the Service is always started. The Throw message is always displayed in the Event logs tough

In C#, I used a code this to accomplish what I want. My question is how I can implement something similar in the PS Service. At least calling he Stop() method would suffice.

protected override void OnStart(string[] args) {
  try {
    // Start your service
  catch (Exception ex) {
    // Log exception
    this.ExitCode = 13816;

The service host is currently suppressing errors. They are written to the event log but it’s allowing the service to continue starting up.

I’ve opened an enhancement for this.

I was thinking the best way to tackle this would be to set the $this variable to point to the same ServiceBase object, so whenever there is an irrecoverable error, the OnStart PS function could execute:


and then the OnStop() function would be called.

The above would be similar to the Event handlers for Windows Forms where $this points to the object being manipulated

Is there an ETA for solving this?

Sorry for the delay. I can get something out this week to address this. Expect something near the end of the week.