- 1 year ago
Powershell script as a Topshelf/Windows service
To create a PowerShell script that runs as a Topshelf/Windows service, you can use a combination of PowerShell and the Topshelf library. Topshelf is a .NET library that simplifies the creation of Windows services using C# or other .NET languages. Since PowerShell can work with .NET assemblies, you can use it in conjunction with Topshelf to create and install the service.
Here's a step-by-step guide to creating a PowerShell script that runs as a Topshelf/Windows service:
Install Topshelf:
First, you need to install the Topshelf NuGet package. Open a PowerShell window and run the following command to install Topshelf:powershellInstall-Package Topshelf
Create the PowerShell Script:
Create a new PowerShell script (e.g.,MyService.ps1
) and define the logic you want to run as a service. For example, you might have a script that writes a log entry every few seconds:powershell# MyService.ps1
while ($true) {
Write-Output "Service is running at $(Get-Date)"
Start-Sleep -Seconds 5
}
Wrap PowerShell Script with C#:
To use the PowerShell script with Topshelf, you'll need to create a C# wrapper to host the PowerShell script as a service. Create a new C# project and add a reference to theSystem.Management.Automation
assembly. Here's an example of the C# wrapper code:csharpusing System;
using System.Management.Automation;
using Topshelf;
class Program
{
static void Main(string[] args)
{
HostFactory.Run(x =>
{
x.Service<MyService>(s =>
{
s.ConstructUsing(name => new MyService());
s.WhenStarted(service => service.Start());
s.WhenStopped(service => service.Stop());
});
x.RunAsLocalSystem();
x.SetDescription("My Topshelf Service Description");
x.SetDisplayName("MyTopshelfService");
x.SetServiceName("MyTopshelfService");
});
}
}
public class MyService
{
private PowerShell _powerShell;
public MyService()
{
_powerShell = PowerShell.Create();
_powerShell.AddScript(".\\MyService.ps1");
}
public void Start()
{
_powerShell.BeginInvoke();
}
public void Stop()
{
_powerShell.Dispose();
}
}
Build the C# Project:
Build the C# project to generate the executable (MyTopshelfService.exe
).Install the Service:
Open an elevated (administrator) PowerShell window and navigate to the folder containing theMyTopshelfService.exe
executable. Run the following command to install the service:powershell.\MyTopshelfService.exe install
Start the Service:
After installation, start the service using:powershell.\MyTopshelfService.exe start
Stop and Uninstall the Service:
To stop and uninstall the service, use the following commands:powershell.\MyTopshelfService.exe stop
.\MyTopshelfService.exe uninstall
With this approach, you have created a Topshelf/Windows service that runs your PowerShell script as a service. The C# wrapper acts as the hosting process for the PowerShell script and handles the service lifecycle using Topshelf.