Create a windows service using PowerShell
Window PowerShell provides a number of helpful CmdLets for managing windows services, such as
And create a new Windows Service using PowerShell “New-Service” CmdLet is very easy. The parameters description of CmdLet can be easily found on MSDN website, so I will not provide it there. I will just provide syntax and example of how it’s used in my project.
The syntax for creating new windows service using PowerShell is following
New-Service [-Name] <String> [-BinaryPathName] <String> [-Credential <PSCredential> ] [-DependsOn <String> ] [-Description <String> ] [-DisplayName <String> ] [-StartupType <ServiceStartMode> ] [ <CommonParameters>]
You can always type the command in your PowerShell window, but if you need to create the same service more than one time it’s better to create script and save it somewhere, for example as part of the project you want to install.
Below is the example of script I used in my recent project to create windows service using PowerShell
I will explain the code in details:
If you already have service installed, you probably want it to be uninstall first (in fact you can just override your binaries and use the same service, but I prefer delete/create service). So at the line #3 I verified if the service already exists and if it exist I get WMI object Win32_service and remove the service.
Line #11: If no service with the provided name exists just do nothing.
If your service does not require to be run under some service account you do not need the following code
but in my case service should be running under service account. In the code above I created PSCredential object with username and password provided as plain text. But if for some reasons your organization not allow it, you can use the following code to ask credentials from the user who will execute script
in that case you will get window asking you for username and password
And finally at the line #19 you create a new Windows Service using PowerShell CmdLet New-Service providing all parameters you need
More code samples at: https://github.com/yaplex/CodeSamples