PrimalScript 2018 supports advanced functionality for Windows services written in PowerShell and packaged with PrimalScript 2018 or PowerShell Studio 2018. While your old code will still work unmodified with this packager engine as it detects the presence of the new functions, it is a good idea to revamp your code to use the new template.
You can find the new template under File, New, PowerShell Service as shown below:
The new template features three preset functions:
Start-MyService | This function is called when your service starts. You should place all initialization code for your service here. |
Invoke-Myservice | This is your service’s main loop. Take a minute to look at the template to understand the process – sleep – process cycle as your service executes. |
Stop-MyService | This function is called when your service is asked to stop by the operating system or when using Stop-Service. You can see some management code in here that will allow your main service loop to exit gracefully. Place code to close connections and release resources here. |
Please do not rename these functions. You can add your own functions as you see fit, but these three functions and their names are essential to make your service execute properly once packaged.
Please note that the main service thread is forcefully terminated after you exit the Stop-MyService function. Make sure you terminate running jobs and secondary runspaces here; otherwise the service process may hang and not exit properly.
As some modules create their own threads, jobs, runspaces, etc. it is also a good idea to use remove-module for any modules you load implicitly or explicitly. The script itself does not operate as a service, but you could dot source it from a test script to execute the functions for testing.
Ultimately, to make a real Windows service, you need to package your script with a PowerShell Windows Service engine as shown here:
As illustrated in a previous blog article, the <service>.exe /i and <service>.exe /u command line parameters can be used to self-install / uninstall the service on your machine.
View this article for information on using the Pause and Continue events.
Feedback
If you have any questions, concerns or feedback you are, as always, more than welcome to visit our support forum and post a message in the appropriate section.
1 comment on “New PowerShell Service Template for PrimalScript 2018”
Comments are closed.