Run batch file as a Windows service
Asked Answered
S

9

204

In order to run one application, a batch file has to be kicked off (which does things like start Jetty, display live logs, etc). The application will work only if this batch file is running. I am hence forced to have this batch file running and not logout from the Windows server.

Can this batch file be run as a service? I am experimenting with one of the suggestions from a similar question.

Sprit answered 6/1, 2009 at 4:2 Comment(6)
Batch programming is on-topic for Stack Exchange.Claycomb
Good question. +1. Moderators are too angry... Also I have another good answer, but question closed ((Sortition
I use this RunAsService instead: runasservice.com. It's much, much simpler to use. No XML configuration nonsense. Basically this just gives you the RunAsService.exe executable, which wraps any console application with command line arguments as a service. I use this to run Cygwin bash scripts as services!!! Unfortunately, this simple tool appears to be closed-source.Joellejoellen
nominating to re-open on the basis of "software tools commonly used by programmers". Which the answer to this question definitely is. Also bear in mind this is the first Google result when searching for "windows start batch file as a service", so whether it's within the narrow scope that some moderators thing is 'on topic' the rest of the world thinks it is. I vote for pragmatism over dogmatism here.Floater
A similar question can be found at serverfault serverfault.com/questions/54676/…Bifacial
RunAsService is now available on GitHub: github.com/luisperezphd/RunAsServiceGigi
A
194

NSSM is totally free and hyper-easy, running command prompt / terminal as administrator:

nssm install "YourCoolServiceNameLabel"

then a dialog will appear so you can choose where is the file you want to run.

to uninstall

nssm remove "YourCoolServiceNameLabel"
Aerial answered 8/11, 2012 at 17:21 Comment(5)
In my case I just gave command ./nssm install serviceA but when I tried to start my service from control panel Services, it got paused and I got an error "The service did not return an error this could be window internal error" what should I do now?Pensionary
do you know if there is a way to give nssm all the necessary args at input to avoid the popup data entry -- i am trying to automate the process ?Theft
NSSM keeps getting deleted at some of our customers by GDATA antivirus. Yes, I know, whitelisting ... but customers don't do what's good for them. That's the sad truth.Calmas
@Theft you can first create a service with "nssm create <service_name> <application_path> <application_arguments>" and then set other parameters (e.g. "nssm set <service_name> AppDirectory <app_directory>")Picrite
I tried this in Windows Server 2022. When running the service manually, it worked but NSSM went crazy and kept opening and closing shells until I manually killed the NSSM process. When rebooting, the service started correctly and NSSM didn't go crazy but this time, the Antimalware process took 100% of the CPU until I manually killed the NSSM process. I'm thinking of using sc create instead.Passacaglia
L
50

There's a built in windows cmd to do this: sc create. Not as fancy as nssm, but you don't have to download an additional piece of software.

sc create "ServiceName" start= demand displayname= "DisplayName" binpath= [path to .bat file]

Note

  • start=demand means you must start the service yourself. Options include: boot, system, auto, demand, disabled, delayed-auto
  • whitespace is required after =
  • I did encounter an error on service start that the service did not respond in a timely manner, but it was clear the service had run the .bat successfully. Haven't dug into this yet but this thread experienced the same thing and solved it using nssm to install the service.
Lesh answered 25/7, 2018 at 18:51 Comment(12)
Windows appears to not run .bat files as services.Shipe
@Shipe - Mine was working yesterday on a couple machines. Are you experiencing something specific? I did encounter an error that the service didn't respond it a timely manner on start, but the .bat file was to startup Kibana node.js server and it was running successfully even with the error. Guys in this thread seemed to experience the same thing but didn't with nssm. https://mcmap.net/q/129371/-elastic-kibana-install-as-windows-serviceLesh
In my case the files the batch file is supposed to create are not created and the programs are not running, so I have to assume it's not starting it. I managed to work around it by creating the service to run cmd.exe /C <batchfile> instead. Note that I'm using Windows 10, so this may be some new "security" thing.Shipe
@Shipe I just got it running on win10 1803 no problem, starts up my node.js server. Does the bat file create the files and run the services when called from cmd or powershell? Do you get any msg boxes when you go to start the service? Does your service have permission to those directories? You could add some error logging in the bat by writing to a local logfile, see if that's working.Lesh
Well if it's definitely supposed to work then I'll take a look at it again at some point. For now filtering it through cmd appears to be working and I don't really want to touch it until the critical need for it is done. Thanks for the help!Shipe
Get "Error 1053: The service did not respond to the start or control request in a timely fashion."Heighten
@AlexKlaus if you read my 3rd bullet point I experienced something similar but the service still started. Linked issue solved with using nssmLesh
If running from powershell, use the full filename sc.exe. As the error will tell you, sc is an alias for Set-Content.Makowski
Set-Content : A positional parameter cannot be found that accepts argument 'binpath='.Louise
@Louise can you post what you're trying to run? Also here's the documentation with some examples. learn.microsoft.com/en-us/previous-versions/windows/it-pro/…Lesh
Error 1053: The service did not respondCalibrate
in place of demand as start type we can specify any of these as the start type (boot, system, auto, demand, disabled, delayed-auto)Scrivner
K
15

No need for extra software. Use the task scheduler -> create task -> hidden. The checkbox for hidden is in the bottom left corner. Set the task to trigger on login (or whatever condition you like) and choose the task in the actions tab. Running it hidden ensures that the task runs silently in the background like a service.

Note that you must also set the program to run "whether the user is logged in or not" or the program will still run in the foreground.

Koontz answered 18/11, 2018 at 17:34 Comment(3)
This was the solution for me. Simply clicking the "Hidden" option achieved my goal.Westleigh
For me it was a perfect solutionAyeshaayin
Worked like a charm. For those who want to start a python script in a "virtual environment" in combination with a (hidden) task, see this answer: https://mcmap.net/q/129372/-activate-virtualenv-and-run-py-script-from-batFritzfritze
K
12

On Windows 2019 Server, you can run a Minecraft java server with these commands:

sc create minecraft-server DisplayName= "minecraft-server" binpath= "cmd.exe /C C:\Users\Administrator\Desktop\rungui1151.lnk" type= own start= auto

The .lnk file is a standard windows shortcut to a batch file.

--- .bat file begins ---

java -Xmx40960M -Xms40960M -d64 -jar minecraft_server.1.15.1.jar

--- .bat file ends ---

All this because:

service does not know how to start in a folder,

cmd.exe does not know how to start in a folder

Starting the service will produce "timely manner" error, but the log file reveals the server is running.

If you need to shut down the server, just go into task manager and find the server java in background processes and end it, or terminate the server from in the game using the /stop command, or for other programs/servers, use the methods relevant to the server.

Kinky answered 31/12, 2019 at 18:20 Comment(3)
if you read it properly, you'll notice it contains the perfect answer, relevant to an exampleKinky
@JeremyJStarcher I think this is actually the best answer on here. It just isn't explained all that well. But the answer is to use binpath="cmd.exe /C [some batch file]"Amando
didn't work for me. Finally did it with nssm.Broadleaf
J
4

Since NSSM is no longer maintained, you can consider using WinSW. It has binaries that would work with or without .Net.

Basically you create an XML file and then install it. Here is a sample of a minimal XML:

<service>

  <!-- ID of the service. It should be unique across the Windows system-->
  <id>myapp</id>

  <!-- Path to the executable, which should be started -->
  <!-- CAUTION: Don't put arguments here. Use <arguments> instead. -->
  <executable>%BASE%\myExecutable.exe</executable>

</service>

And then you can install and start it:

winsw install myapp.xml
winsw start myapp.xml
Juliajulian answered 1/5, 2021 at 1:33 Comment(3)
does not work for batch files (v3)Noe
@Noe what are "batch files (v3)" ?Juliajulian
I meant WinSW v3.0.0-alpha.10 (in windows 10)Noe
C
3

As Doug Currie says use RunAsService.

From my past experience you must remember that the Service you generate will

  • have a completely different set of environment variables
  • have to be carefully inspected for rights/permissions issues
  • might cause havoc if it opens dialogs asking for any kind of input

not sure if the last one still applies ... it was one big night mare in a project I worked on some time ago.

Ciao answered 6/1, 2009 at 4:36 Comment(0)
A
3

While it is not free (but $39), FireDaemon has worked so well for me I have to recommend it. It will run your batch file but has loads of additional and very useful functionality such as scheduling, service up monitoring, GUI or XML based install of services, dependencies, environmental variables and log management.

I started out using FireDaemon to launch JBoss application servers (run.bat) but shortly after realized that the richness of the FireDaemon configuration abilities allowed me to ditch the batch file and recreate the intent of its commands in the FireDaemon service definition.

There's also a SUPER FireDaemon called Trinity which you might want to look at if you have a large number of Windows servers on which to manage this service (or technically, any service).

Alienee answered 6/1, 2009 at 11:6 Comment(0)
C
2

Install NSSM and run the .bat file as a windows service. Works as expected

Calibrate answered 20/2, 2021 at 14:51 Comment(0)
S
0

My easest way is using opensource svcbatch (https://github.com/mturk/svcbatch/) as wrapper of CMD(BAT) in sc :

sc create myservice binPath= ""%cd%\svcbatch.exe" myservice.bat"

Spousal answered 13/8, 2022 at 10:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.