Start-sleep => Service does not start

Hi,

I just create a Test Script for a New Service.
The Service does not start, until i remove the start-sleep function.

function StartService()

{

(get-date).ToString() | out-file -file "C:\_Log\TestLog.log" -Append

Start-Sleep -Seconds 10

}

function StopService()

{

}

My Goal is to run a Script every 5 Minutes, but would not use any external modules for that.

Thanks

Regards
Daniel

The StartService function needs to return before the service will fully start. The service control manager will timeout after a certain amount of time if the StartService function doesn’t return. If service control manager reporting that there was an error starting the service?

Hi Adam,

you are right, the Service has never been startet. (Timeout)
Can you provide me an sample Script for that?

Thanks

Regard
Daniel

Daniel,

As Adam states, you cannot put the periodic process in the OnStart function, otherwise it will never start. That function is supposed to run only once when the service is started and cannot have much delay. The way to perform what you want is by setting a Timer (of 10 seconds in your case) and attach an EventHandler routine so it will execute periodically when triggered at that interval.

Although written in C#, so it can be easily ported to PS, this code shows a similar solution that you can implement. It was extracted from https://www.c-sharpcorner.com/article/create-windows-services-in-c-sharp/

This link shows how to set a timer enabled event in PS: https://devblogs.microsoft.com/scripting/use-asynchronous-event-handling-in-powershell/

Good luck !!!

VICTOR