Windows run exe as service

Many existing answers include human intervention at install time. This can be an error-prone process. If you have many executables wanted to be installed as services, the last thing you want to do is to do them manually at install time.

Towards the above described scenario, I created serman, a command line tool to install an executable as a service. All you need to write (and only write once) is a simple service configuration file along with your executable. Run

serman install <path_to_config_file>

will install the service. stdout and stderr are all logged. For more info, take a look at the project website.

A working configuration file is very simple, as demonstrated below. But it also has many useful features such as <env> and <persistent_env> below.

<service>
  <id>hello</id>
  <name>hello</name>
  <description>This service runs the hello application</description>

  <executable>node.exe</executable>

  <!-- 
       {{dir}} will be expanded to the containing directory of your 
       config file, which is normally where your executable locates 
   -->
  <arguments>"{{dir}}\hello.js"</arguments>

  <logmode>rotate</logmode>

  <!-- OPTIONAL FEATURE:
       NODE_ENV=production will be an environment variable 
       available to your application, but not visible outside 
       of your application
   -->
  <env name="NODE_ENV" value="production"/>

  <!-- OPTIONAL FEATURE:
       FOO_SERVICE_PORT=8989 will be persisted as an environment
       variable to the system.
   -->
  <persistent_env name="FOO_SERVICE_PORT" value="8989" />
</service>

If you want to run an application as a Service in Windows OS, then continue reading this tutorial. As you know, the common methods to run a program at Windows Startup is to place the program at Windows Startup folder, or to run the program at startup by using the Windows Registry, or to start the application using the Task Scheduler. Although these methods are effective in most cases, in some cases there is a need to run an application at startup as a Windows service, before user’s login or user’s interaction.

This tutorial contains step-by-step instructions on how to create a Windows service with any program in Windows 10, 8, 7 & Server OS.

How to Run Any Application as a Windows Service.

Method 1. Run Application as Windows Service by using RunAsService utility.
Method 2. Run Program as Service by using NSSM utility.

Method 1. How to run any application as a Windows Service with ‘Run As Service’ Utility.

The first method to create a user-defined service from any program is to use the «RunAsService» utility.

1. Download the RunAsService tool to your PC.
2. Move or Copy the downloaded file RunAsService.exe, to the root folder of drive C:\. *

* Note (Important): You can place the «RunAsService.exe» tool to any location you want on the disk, but make sure to keep the tool in the same location in order the installed service(s) to continue functioning.

Run as Windows Service

3. Open Command Prompt as Administrator.
4. In the command prompt type: cd\

5. Now install the application you want as a service, by using the following command: *

  • RunAsService install «ServiceName» «Display-Name« «PathToExecutable«

Notes:

1. In the above command replace the values in red letters as follows:

Name: Type a Name for the Service you want to create. You can use the Service Name to start or stop the service manually on the future by giving the «net start» or «net stop» commands.

Display Name: If you want, type a different Name for the Windows Services list. This is how the service name will be displayed in the services list. If no «Display Name» is specified, then the Display Name will be the same as the «ServiceName» of the service you create.

PathToExecutable: Type the full path of the application that you want to run as a Windows service.

For example: To install the «Notepad.exe» application as a Windows service with the name «Notepad», give the following command:

  • RunAsService install «Notepad» «C:\Windows\System32\notepad.exe»

RunAsService install service

2. If after executing the above command you receive the message «An app needs the .Net Framework 2.0 feature to work», click Download and install this feature, or download the .Net Framework 2.0 from the Microsoft download center.

image

6. After the command execution, a new Windows Service will appear in the services list, with the name you specified in the «RunAsService» command. To run the newly created service at startup:

a. Right-click on the service and choose Properties.

Servise list

b. Ensure that the Startup type is set to Automatic.

image

c. Restart your PC, to test the service. *

* Notes:
1. You can start or stop the service at any time you want, by running the «net start» or the «net stop» commands in Command Prompt (Admin).
2. If you want to uninstall the installed service in the future:

a. Stop the service by running this command in Admin Command Prompt:

  • net stop «ServiceName«

e.g. net stop «Notepad»

b. Uninstall the service by giving this command:

  • RunAsService uninstall «ServiceName«

e.g. RunAsService uninstall «Notepad»

RunAsService Uninstall Service

Method 2. How to run any program as a service by using NSSM.

The second method to run any application as a service in Windows, is by using the Non-Sucking Service Manager tool.

1. Download NSSM.
2. Extract the downloaded ZIP file.
3. Rename the extracted folder (e.g. «nssm-2.24»), to NSSM.
4. Copy the NSSM folder to the root folder of drive C:\
5. Open Command Prompt as Administrator and navigate to the NSSM folder, by typing the following commands in order (Press Enter after typing each command):

  • cd\
  • cd nssm

6. Now according to your Windows version (32 or 64bit), navigate to the one of two contained subfolders, by type the corresponding command (and press Enter).

  • If you own 64Bit Windows, type: cd win64
  • If you own 32Bit Windows, type: cd win32

7. Now type the following command: *

  • nssm install

Install Service nssm

8. In the window that opens:

8a. Press the tree (3) dots button next image to PATH and select the application’s executable that you want to run as a service.

NSSM Service Installer

8b. When done, type a Name for the new service and click Install service.

Install Service with NSSM

8c. Click OK to the message «Service installed successfully» and you’re done! *

* Notes:
1. After installing the service with the NSSM service installer, a new Windows Service will appear in the services list, with the name you specified in the Service name, than can be managed as any other Windows service.
2. To uninstall the service in the future:

a. Follow the steps 5 & 6 above, and then type the following command: *

  • nssm remove ServiceName

* Note: Where ServiceName = the name of the service you created, using the NSSM utility.
e.g. nssm remove NOTEPAD in this example.

nssm remove service

b. Finally click Yes to Remove the service.

How to Run An Application As Service

That’s it! Let me know if this guide has helped you by leaving your comment about your experience. Please like and share this guide to help others.

There are many third-party tools to run a normal Windows executable as a service.

Bitsum authored such a utility, command line only, called MakeService (now in limited distribution due to abuse).

They are able to do this by using a service stub that then launches the normal Windows executable. That service stub can then control the launched process as necessary in response to start, stop, etc.. service commands.

However, if your application has any interactivity with the user, then you will encounter system service session isolation in NT6+.

It’s sad that we had to discontinue instant download of this freeware utility, but we will still distribute it to those who have legitimate needs. It is available in 32-bit and 64-bit x86 native.

I am sure there are other similar utilities, including Microsoft’s srvany.exe in the Windows Resource Kit, as the accepted answer recommends. It does the same thing as our MakeService did/does.

Follow us on Social Media

Register Exe As Windows Service With Code Examples

Good day, folks. In this post, we’ll examine how to find a solution to the programming challenge titled Register Exe As Windows Service.

To create a Windows Service from an executable, you can use sc.exe: (Run as Admin !!)

sc.exe create <new_service_name> binPath= "<path_to_the_service_executable>"
You must have quotation marks around the actual exe path, and a space after the binPath=.

More information on the sc command can be found in Microsoft KB251192.

Note that it will not work for just any executable: the executable must be a Windows Service (i.e. implement ServiceMain). When registering a non-service executable as a service, you'll get the following error upon trying to start the service:

Error 1053: The service did not respond to the start or control request in a timely fashion.

There are tools that can create a Windows Service from arbitrary, non-service executables, see the other answers for examples of such tools.

Using many examples, we’ve learned how to tackle the Register Exe As Windows Service problem.

Can we run exe as Windows service?

You can execute an .exe from a Windows service very well in Windows XP. I have done it myself in the past. You need to make sure you had checked the option «Allow to interact with the Desktop» in the Windows service properties. If that is not done, it will not execute.15-Mar-2011

How do I register an application as a Windows service?

Steps to create a user-defined service

  • At an MS-DOS command prompt(running CMD.EXE), type the following command: Console Copy.
  • Run Registry Editor (Regedt32.exe) and locate the following subkey:
  • From the Edit menu, select Add Key.
  • Select the Parameters key.
  • From the Edit menu, select Add Value.
  • Close Registry Editor.

How do I run a service exe?

Go to «System32». Look for «services» or «services. msc». Open it.Use the Run dialog.

  • Press the ⊞ Win + R keys simultaneously.
  • Type services. msc .
  • Press OK or hit ↵ Enter .

How do I run a command as Windows service?

Use a command prompt

  • From the start menu, right-click Command prompt, select More, and select Run as Administrator.
  • Type one of the following, where ServiceName is the name of the BizTalk Server service you want to start, stop, pause, or resume: To start a service, type: net start ServiceName. To stop a service, type:

How do I create a dummy window service?

1 Answer

  • Create a dummy.bat file in C:\ with contents «pause»
  • Extract nssm.exe (x86 or x64) to C:\Windows\nssm.exe.
  • Run «nssm install»
  • Path: C:\dummy.bat.
  • Service name – As you wish!
  • Hit «Install service»

How do I create a Windows service?

Create a service

  • From the Visual Studio File menu, select New > Project (or press Ctrl + Shift + N ) to open the New Project window.
  • Find and select the Windows Service (. NET Framework) project template.
  • For Name, enter MyNewService, and then select OK. The Design tab appears (Service1.

How do I run an exe in the background?

Right-click the program (it’ll actually be a link file, with a little arrow in the corner of the icon) and select Properties . Go to the Shortcut tab of the window that opens (if you didn’t start there). One of the options will be Run: with a drop-down next to it (probably saying Normal window ).18-Jan-2017

What is a Windows service application?

Microsoft Windows services, formerly known as NT services, enable you to create long-running executable applications that run in their own Windows sessions. These services can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface.15-Sept-2021

How do I create a Windows service from a batch file?

Linked

  • 129.
  • Run Batch File On Start-up.
  • Elastic Kibana – install as windows service.
  • Run Java application as a service.
  • Spring boot JAR as windows service.
  • Run PHP script in background on Apache start/restart(Windows Server)
  • Running Python Program as Windows Service with a specific conda virtual environment.

How do I create a Windows service in PowerShell?

Install and uninstall itself (using Windows PowerShell service management functions). Start and stop itself (using the same set of functions). Contain a short C# snippet, which creates the PSService.exe that the SCM expects (using the Add-Type command). Make the PSService.exe stub call back into the PSService.

Follow us on Social Media

Иногда может потребоваться взять исполняемый файл и зарегистрировать его в качестве службы Windows. Для этого есть несколько способов, я обычно пользуюсь двумя из них.

Sc.exe

Для создания и службы из командной строки можно использовать программу SC (Sc.exe). SC представляет из себя утилиту командной строки, которая реализует вызовы ко всем функциям интерфейса прикладного программирования (API) управления службами Windows. С ее помощью можно производить любые действия со службами —  просматривать состояние, управлять (запускать, останавливать и т.п.), изменять параметры, а также создавать новые службы.

При создании службы с помощью SC нет необходимости вручную создавать записи в реестре и затем перезагружать компьютер, чтобы обеспечить обновление базы данных диспетчером служб. Также SC позволяет указать имя удаленного компьютера, что дает возможность управлять службами как на локальном, так и на удаленном компьютере.

Для создания нового сервиса запускаем команду Sc create. Она создает запись службы в реестре и в базе данных диспетчера служб. Sc create имеет следующий синтаксис:

sc create [ServiceName] [binPath= ] <параметр1= > <параметр2= >

ServiceName — указывает имя, которое будет присвоено разделу службы в реестре. Имейте в виду, что это имя отличается от отображаемого имени службы (имени, которое отображается в оснастке «Services»);
binPath — указывает путь к исполняемому файлу службы.

Для примера создадим службу MyService, укажем отображаемое имя My New Service, зададим тип службы и поставим ее на авто-запуск:

Sc create MyService binPath=C:\MyService\MyService.exe DisplayName=″My New Service″ type=own start=auto

Затем откроем оснастку «Services» и посмотрим результат.

оснастка Службы

Изменять параметры уже созданной службы можно командой Sc config. Например, мне не понравилось отображаемое имя службы и я хочу его изменить:

Sc config MyService DisplayName=″My Service″

Ну и полностью удалить службу можно вот так:

Sc delete MyService

создание, изменение и удаление службы Windows

PowerShell

PowerShell может почти все 🙂 , в том числе и управлять службами Windows. Создать новую службу можно с помощью командлета New-Service. Создадим такой же сервис, как и в предыдущем примере, только добавим к нему описание (Description):

New-Service -Name MyService -BinaryPathName C:\MyService\MyService.exe`
-DisplayName ″My New Service″ -Description ″Very Important Service !!!″

Изменить параметры службы можно командлетом Set-Service:

Set-Service -Name MyService -Description ″Not Very Important Service″ -StartupType Manual

создание и изменение служб с помощью PowerShell

В принципе PowerShell имеет примерно такой же функционал как и Sc.exe, разве что позволяет добавить описание. А вот для удаления служб в PS простого способа нет, придется воспользоваться вот такой конструкцией:

(Get-WmiObject win32_service -Filter ″name=′MyService′″).delete()

Поэтому лично я предпочитаю использовать Sc.exe.

  • Windows root system 32 hal dll
  • Windows repair скачать бесплатно на русском языке
  • Windows rising output перевод на русский
  • Windows repair windows 7 что делать и как исправить
  • Windows repair toolbox как пользоваться