How do I run a PowerShell script as a service?


I created the script below to check my application’s port 2025 and log the number of connections.

I need this script to run as a service on Windows with the name netstat_2025. Does anyone know if there is such a possibility?

I do not want to use the Task Scheduler, but instead run the script as a service on Windows.

script SCTT521CTO.ps1

script service.ps1


My original answer failed to take into account that you still need to implement the service control interfaces, which powershell.exe does not implement. I did look into some other methods of running a PowerShell script as a service, however.

One of the easier tools I came across that does this for you is nssm You can use nssm (Non-Sucking Service Manager) to register a new service and have it run your PowerShell script. You’ll need to make sure your script’s main logic runs within an infinite loop (as most long running programs or services do), and then you can use nssm to register a new service that will run your PowerShell script. Below is an example of putting your code into a main loop that doesn’t terminate:

To register your script as a PowerShell service, you can use the following PowerShell code (note that if you install with Chocolatey, nssm will already be on the PATH, not sure if it is when you manually install):

Your service should now be installed and able to be controlled like any other Windows service. The way this works is instead of registering powershell.exe as a service directly, it registers nssm.exe as the service executable instead, which does implement the correct service control handlers, and then runs whatever program you configured it to for this service (in this case, calling your script with powershell.exe).


How do I run a PowerShell script as a service? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply