My application has a self-update feature.
It downloads a new version by itself, and when this occurrs at the end of the download process the JVM exits with code 2.
Is possible to configure the Procrun to auto-restart the service if the exit code 2 occurrs ?
I solved using another tool for running my application as a service: NSSM
With it, I register a parameter to NSSM like this:
nssm install my-service-name "java -jar snapshot.jar"
nssm set my-service-name AppEvents "Start/Pre" "cmd /c copy /y my-app.jar snapshot.jar"
nssm set my-service-name AppExit Default Exit
nssm set my-service-name AppExit 2 Restart
nssm set my-service-name AppDirectory "c:\path\to\my\app"
So, this lines will:
Register a windows service named my-service-name who launches a copy of my jar (java) application.
Set a parameter to NSSM to copy my-app.jar to snapshot.jar before start the service.
Set a parameter to NSSM to specify that, when my app terminates the default behavior is assuming that the service must stop
Set a parameter to NSSM to specify that, when my app terminates with the exit code 2 it must be restarted (my java application) and the service must continue to running.
Set a parameter to NSSM to specify that my app will using the current directory as c:\path\to\my\app
Another solution is creating a batch file to be on loop, like this (I called it run-app.bat):
#echo off
set java=C:\Program Files (x86)\Java\jre1.8.0_192
:start
copy /y my-app.jar snapshot.jar
if %errorlevel% equ 0 goto :run
if %errorlevel% neq 0 goto :end
:run
"%java%\bin\java.exe" -jar snapshot.jar --start
if %errorlevel% equ 2 goto :start
:end
exit /b %errorlevel%
And using the NSSM to register the service in a simple way:
nssm install my-service-name "cmd /c run-app.bat"
nssm set my-service-name AppDirectory "c:\path\to\my\app"
In this scenario, the NSSM will just launch my batch run-app.bat.
The batch will stay on loop (restarting my app) while the application exits with code 2.
Related
I´m trying to launch an application (pentaho business intelligence server) but the .bat file won´t run. It doesn´t throw any error or anything, the command prompt pops up and then disappears right after. Then I figured out that it´s tomcat that isn´t running, but no error is being logged in the tomcat logs folder.
This is what shows in the command prompt when I start the bat file (I had to add a pause to see where it goes before exiting)
I also run the catalina.bat file and I also could see that the last thing it tried to run was this CLASSPATH, and seems like it was trying to open this tomcat-juli.jar and bootstrap.jar, but is not working somehow.
I´m not really familiar with any of this, so I´m not sure if this is normal, could you point me to the right direction on how to solve this?
EDIT 1. I was suggested to add the code of the bat file in question, here it is:
#echo off
setlocal
cd /D %~dp0
cscript promptuser.js //nologo //e:jscript
rem errorlevel 0 means user chose "no"
if %errorlevel%==0 goto quit
echo WScript.Quit(1); > promptuser.js
call set-pentaho-env.bat "%~dp0jre"
cd tomcat\bin
set CATALINA_HOME=%~dp0tomcat
SET BITS=64
SET DI_HOME="%~dp0pentaho-solutions\system\kettle"
set CATALINA_OPTS=-Xms2048m -Xmx6144m -XX:MaxPermSize=256m -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -Dfile.encoding=utf8 -DDI_HOME=%DI_HOME%
rem Make sure we set the appropriate variable so Tomcat can start (e.g. JAVA_HOME iff. _PENTAHO_JAVA_HOME points to a JDK)
if not exist "%_PENTAHO_JAVA_HOME%\bin\jdb.exe" goto noJdk
if not exist "%_PENTAHO_JAVA_HOME%\bin\javac.exe" goto noJdk
set JAVA_HOME=%_PENTAHO_JAVA_HOME%
set JRE_HOME=
goto start
:noJdk
rem If no JDK found at %_PENTAHO_JAVA_HOME% unset JAVA_HOME and set JRE_HOME so Tomcat doesn't misinterpret JAVA_HOME == JDK_HOME
set JAVA_HOME=
set JRE_HOME=%_PENTAHO_JAVA_HOME%
:start
call startup
:quit
endlocal
pause
EDIT 2. After some research I'm sure the problem is that tomcat doesn't start, changing the title of the question.
Things that I've already tried:
Changing the port from 8080 to 8081.
Setting _PENTAHO_JAVA_HOME environment.
Opening tomcat (startup.bat) and catalina.bat from the command prompt, it just tells me it runs it but exits after CLASSPATH (exactly the same as the screenshot provided).
Checking the logs file in tomcat, it's empty
I managed to make it work, I uninstalled java 11 and installed java 8 (this version is compatible with pentaho), then I changed the environment _PENTAHO_JAVA_HOME to this java 8, that made it work. But now I can only make it work from the tomcat startup.bat and not from the file start-pentaho.bat, so I guess there is still a way to make it work as it was meant to.
I've written this code to restart an application when it crashes:
#ECHO OFF
:B
SET MyProcess=AL.Distributore.exe
TASKLIST | FINDSTR /I "%MyProcess%"
IF ERRORLEVEL 1 (GOTO :StartScripts) ELSE (timeout 120 /nobreak >nul)
GOTO :B
:StartScripts
::: //-- Put in the full path to the batch scripts to call
::: //-- Be sure the security context this process runs as has access to execute the below-called batch scripts
if exist D:\Acqualogica\Applicazione\AL.Distributore.exe (START D:\Acqualogica\Applicazione\AL.Distributore.exe)
GOTO :B
It works fine if I start with a double click, but I need to run this on the background when the PC starts. I've tried to put the shortcut to C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup, create a key in the register for autostart, but nothing starts (or works).
OS: Windows 7
How can I do it?
You can do this using the task scheduler. This feature can be configured using the Windows settings, or by commandline (using schtasks.exe (/SC OnStart)), but for a start, I'd advise you the Windows settings tool (in the "Trigger" section, you'll see an "OnStart" possibility).
I am using the sc command to remotely restart a process under runas. This works perfectly with a service that has no spaces, but if it has spaces, forcing me to use ' inside the runas "command" quotes, it fails and cannot find the service.
I have already checked the properties of this particular service to ensure the service name (it is the same as the display name).
#ECHO OFF
REM Prompt for Domain & Username. Password will be prompted when run.
set /P Domainn=Enter Domain Name:
set /P Usern=Enter Username:
set service=workingservice
REM set service='Not a working service'
REM Define Start Stops
set userrunasstop=runas /profile /user:%domainn%\%usern% "sc \\%domainn% stop %service%"
set userrunasstart=runas /profile /user:%domainn%\%usern% "sc \\%domainn% start %service%"
:optionmenu
CLS
ECHO 1 - Stop Service
ECHO 2 - Start Service
ECHO q - Quit
ECHO.
set /P optionnum=Enter command number:
GOTO option%optionnum%
:option1
REM Stop Client
%userrunasstop%
goto optionmenu
:option2
REM Start Client
%userrunasstart%
goto optionmenu
:optionq
EXIT
This script works great as shown, but when I comment out set service=workingservice and un-comment set service='Not a working service it doesn't work. Also, if I use runas to open its open cmd.exe, I can then successfully run the sc command with quotes around the service name.
I have set up a workaround for this issue by opening up a new command prompt under runas. And in the new command prompt calling another bat file that executes the sc stop service command. This removes the multiple quoting that was causing the error.
I am still working on passing variables from the runas batch file to the sc batch file to allow the %domain% variable to be input into the sc command.
File runas.bat
set /P Domainn=Enter Domain Name:
set /P Usern=Enter Username:
runas /profile /user:%domainn%\%usern% "cmd sc.bat"
File sc.bat (minus all the frills in the original script)
set service='Service with spaces'
sc \\domainname stop %service%
I've found plenty of references on the web for rotating the nginx logs under linux.. just send the USR1 signal to the process. But... unix like signals don't exist on windows and I haven't been able to find any information on this. How can I accomplish the same thing with nginx on windows??
To rotate nginx logs in Windows, create a batch file like this one:
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set YMD=%%c-%%a-%%b)
move C:\path\to\nginx\logs\Access.log C:\path\to\nginx\logs\Access_%YMD%.log
move C:\path\to\nginx\logs\Error.log C:\path\to\nginx\logs\Error_%YMD%.log
call C:\path\to\nginx\nginx -p C:\path\to\nginx -s reopen
That first line just creates a timestamp (credit to Jay)
Then create a scheduled task in Windows to run that batch file how ever often you want to rotate the logs.
If nginx is running as a service (such as through the Windows Service Wrapper described here) you can't simply call nginx commands like nginx -s reopen directly. Instead you have to run the commands as the user who the service is running as.
To do this, create a new user called nginx (for example) and configure both the service and the scheduled task to run as that user. You'll also have to make sure your user has "Logon as a batch job" rights.
If you want to test your rotation script on the command line without having to use a scheduled task you can use
runas /user:nginx "C:\path\to\rotateLogs.bat"
Actually (despite tons of googling) the answer can be found squarely in the doc pages. The command is nginx -s reopen but this only seems to work when running nginx from the command line – currently the only official way to run nginx on Windows at this time.
My next challenge is to figure out how to make this work when running nginx as a windows service as described in the answers to Run nginx as a Windows service.
with windows server 2008 R2, I create this batch file, and I schedule it one time a day at midnight:
#echo off
SET DATE=%date%
SET DAY=%DATE:~0,2%
SET MONTH=%DATE:~3,2%
SET YEAR=%DATE:~6,4%
SET DATE_FRM=%YEAR%-%MONTH%-%DAY%
ECHO %DATE_FRM%
REM ECHO %YEAR%
REM ECHO %MONTH%
REM ECHO %DAY%
move D:\nginx-1.11.1\logs\access.log D:\nginx-1.11.1\logs\access_%DATE_FRM%.log
move D:\nginx-1.11.1\logs\error.log D:\nginx-1.11.1\logs\error_%DATE_FRM%.log
call D:\nginx-1.11.1\nginx -p D:\nginx-1.11.1 -s reopen
1.first create a file to store your log file list, like "nginx_log.lst" with content:
D:\projects\example.com\data\log\access.log
D:\projects\example.com\data\log\error.log
2.save the following content to a bat file such as "nginx_log_rotate.bat":
#echo off
set YMD=%date:~0,4%%date:~5,2%%date:~8,2%
set LOG_FILE=
FOR /F "eol=; delims=, " %%i in (nginx_log.lst) do (
echo "%%i"
move "%%i" "%%i.%YMD%"
)
pushd C:\tools\nginx
nginx -s reopen
popd
pause
#echo on
3. create a schedule task to run the bat as you wish
I wrote small utility which rotates log files after stoppig nginx (which is running as windows service) for few seconds.
It had specific requirement to stop , then copy log files and then restart service nighly basis. You can download the code and change it whatever way you want.
Code is here : http://mandar.tumblr.com/post/5419161330/nginx-logrotate-windows
Thanks
For some reasons below batch file worked for me.
For /f "tokens=1-4 delims=/ " %%a in ('date /t') do (set YMD=%%c-%%a-%%b)
move .\logs\access.log .\logs\access.%YMD%.log
move .\logs\error.log .\logs\error.%YMD%.log
nginx.exe -s reload
It's more or less same as Tom's answer above.
#echo off
SET DATE_FRM=%date%
REM set path of Nginx root folder.
SET NGINX_PATH="E:\nginx-1.14.2"
REM create old_logs folder if not exists , we will move old logs in this folder.
if not exist "%NGINX_PATH%\old_logs\NUL" mkdir "%NGINX_PATH%\old_logs"
REM move error.log in old_logs from logs folder and rename it
move %NGINX_PATH%\logs\access.log %NGINX_PATH%\old_logs\access_%DATE_FRM%.log
move %NGINX_PATH%\logs\error.log %NGINX_PATH%\old_logs\error_%DATE_FRM%.log
REM reopn nginx logs, this will create new error.log for nginx.
call %NGINX_PATH%\nginx -p %NGINX_PATH% -s reopen
REM compress error%DATE_FRM%.log, this will create error_%DATE_FRM%.log.zip file.
powershell Compress-Archive -Path %NGINX_PATH%\old_logs\access_%DATE_FRM%.log -DestinationPath %NGINX_PATH%\old_logs\access_%DATE_FRM%.log.zip -force
powershell Compress-Archive -Path %NGINX_PATH%\old_logs\error_%DATE_FRM%.log -DestinationPath %NGINX_PATH%\old_logs\error_%DATE_FRM%.log.zip -force
REM delete error%DATE_FRM%.log from old_logs.
del %NGINX_PATH%\old_logs\access_%DATE_FRM%.log
del %NGINX_PATH%\old_logs\error_%DATE_FRM%.log
I use NSSM to manage Nginx on Windows (checked on WhiteHorse). Although this utility has built-in rotate functionality, it probably doesn't work properly. The documentation warns about risk of online rotation.
Two service entries should be configured:
Nginx, and
Nginx Rotate Logs.
The solution doesn't support rotation based on file size or file age. It's possible to setup schedule to rotate logs using nginx -s reopen.
First,
create Nginx Rotate Logs service, using NSSM (note bene: you may use the same command to create main Nginx service).
Command below will create service entry:
nssm install "Nginx Rotate" C:\tools\nginx-1.21.6\nginx.exe
Next lines will configure service step-by-step, oneliner is not available here.
nssm set "Nginx Rotate" AppParameters "-s reopen"
nssm set "Nginx Rotate" AppExit Default Exit
nssm set "Nginx Rotate" AppStdout C:\tools\nginx-1.21.6\logs\access.log
nssm set "Nginx Rotate" AppStderr C:\tools\nginx-1.21.6\logs\error.log
nssm set "Nginx Rotate" AppRedirectHook 1
nssm set "Nginx Rotate" AppRotateFiles 1
nssm set "Nginx Rotate" AppRotateOnline 1
nssm set "Nginx Rotate" AppTimestampLog 1
nssm set "Nginx Rotate" Description "Some description"
nssm set "Nginx Rotate" DisplayName "Nginx Rotate Logs"
nssm set "Nginx Rotate" ObjectName DOMAIN\user "password"
nssm set "Nginx Rotate" Start SERVICE_DEMAND_START
nssm set "Nginx Rotate" Type SERVICE_WIN32_OWN_PROCESS
Then edit service:
nssm edit "Nginx Rotate"
At the last tab you need set:
Event = Log rotation + Before online log rotation
as shown in the picture below.
As a result, this service will be in manual mode. After start it rotates logs and stops.
Second,
create a schedule task.
schtasks /create /sc daily /st 03:30 /tn "Nginx Rotate Logs" /tr "C:\Program Files\PowerShell\7\pwsh.exe -command start-service 'Nginx Rotate Logs'"
Important,
use the same user both for Nginx, Nginx Rotate Logs and Schedule Task.
Usage:
While main Nginx is operating, the schedule task runs once a day, rotating files.
Aux:
You may add a daily task (or add to hook tab) to compress and purge old logs, for example:
# install PSCX module
Install-Module -Name Pscx -AllowPrerelease -AllowClobber
# compress
Get-ChildItem 'C:\tools\nginx-1.21.6\logs\*.log' | Where {$_.lastwritetime -lt (Get-Date).AddDays(-1)} | write-zip
# purge yesterday zip
Get-ChildItem 'C:\tools\nginx-1.21.6\logs\*.zip' | Where {$_.lastwritetime -lt (Get-Date).AddDays(-2)} | Remove-Item -Force
#echo off
net stop nginx
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo move %~dp0\Access.log %~dp0\Old\Access_%fullstamp%.log
move %~dp0\Access.log %~dp0\Old\Access_%fullstamp%.log
echo move %~dp0\Error.log %~dp0\Old\Error_%fullstamp%.log
move %~dp0\Error.log %~dp0\Old\Error_%fullstamp%.log
net start nginx
How can I script a bat or cmd to stop and start a service reliably with error checking (or let me know that it wasn't successful for whatever reason)?
Use the SC (service control) command, it gives you a lot more options than just start & stop.
DESCRIPTION:
SC is a command line program used for communicating with the
NT Service Controller and services.
USAGE:
sc <server> [command] [service name] ...
The option <server> has the form "\\ServerName"
Further help on commands can be obtained by typing: "sc [command]"
Commands:
query-----------Queries the status for a service, or
enumerates the status for types of services.
queryex---------Queries the extended status for a service, or
enumerates the status for types of services.
start-----------Starts a service.
pause-----------Sends a PAUSE control request to a service.
interrogate-----Sends an INTERROGATE control request to a service.
continue--------Sends a CONTINUE control request to a service.
stop------------Sends a STOP request to a service.
config----------Changes the configuration of a service (persistant).
description-----Changes the description of a service.
failure---------Changes the actions taken by a service upon failure.
qc--------------Queries the configuration information for a service.
qdescription----Queries the description for a service.
qfailure--------Queries the actions taken by a service upon failure.
delete----------Deletes a service (from the registry).
create----------Creates a service. (adds it to the registry).
control---------Sends a control to a service.
sdshow----------Displays a service's security descriptor.
sdset-----------Sets a service's security descriptor.
GetDisplayName--Gets the DisplayName for a service.
GetKeyName------Gets the ServiceKeyName for a service.
EnumDepend------Enumerates Service Dependencies.
The following commands don't require a service name:
sc <server> <command> <option>
boot------------(ok | bad) Indicates whether the last boot should
be saved as the last-known-good boot configuration
Lock------------Locks the Service Database
QueryLock-------Queries the LockStatus for the SCManager Database
EXAMPLE:
sc start MyService
net start [serviceName]
and
net stop [serviceName]
tell you whether they have succeeded or failed pretty clearly. For example
U:\>net stop alerter
The Alerter service is not started.
More help is available by typing NET HELPMSG 3521.
If running from a batch file, you have access to the ERRORLEVEL of the return code. 0 indicates success. Anything higher indicates failure.
As a bat file, error.bat:
#echo off
net stop alerter
if ERRORLEVEL 1 goto error
exit
:error
echo There was a problem
pause
The output looks like this:
U:\>error.bat
The Alerter service is not started.
More help is available by typing NET HELPMSG 3521.
There was a problem
Press any key to continue . . .
Return Codes
- 0 = Success
- 1 = Not Supported
- 2 = Access Denied
- 3 = Dependent Services Running
- 4 = Invalid Service Control
- 5 = Service Cannot Accept Control
- 6 = Service Not Active
- 7 = Service Request Timeout
- 8 = Unknown Failure
- 9 = Path Not Found
- 10 = Service Already Running
- 11 = Service Database Locked
- 12 = Service Dependency Deleted
- 13 = Service Dependency Failure
- 14 = Service Disabled
- 15 = Service Logon Failure
- 16 = Service Marked For Deletion
- 17 = Service No Thread
- 18 = Status Circular Dependency
- 19 = Status Duplicate Name
- 20 = Status Invalid Name
- 21 = Status Invalid Parameter
- 22 = Status Invalid Service Account
- 23 = Status Service Exists
- 24 = Service Already Paused
Edit 20.04.2015
Return Codes:
The NET command does not return the documented Win32_Service class return codes (Service Not Active,Service Request Timeout, etc) and for many errors will simply return Errorlevel 2.
Look here: http://ss64.com/nt/net_service.html
You can use the NET START command and then check the ERRORLEVEL environment variable, e.g.
net start [your service]
if %errorlevel% == 2 echo Could not start service.
if %errorlevel% == 0 echo Service started successfully.
echo Errorlevel: %errorlevel%
Disclaimer: I've written this from the top of my head, but I think it'll work.
I have created my personal batch file for this, mine is a little different but feel free to modify as you see fit.
I created this a little while ago because I was bored and wanted to make a simple way for people to be able to input ending, starting, stopping, or setting to auto. This BAT file simply requests that you input the service name and it will do the rest for you. I didn't realize that he was looking for something that stated any error, I must have misread that part. Though typically this can be done by inputting >> output.txt on the end of the line.
The %var% is just a way for the user to be able to input their own service into this, instead of having to go modify the bat file every time that you want to start/stop a different service.
If I am wrong, anyone can feel free to correct me on this.
#echo off
set /p c= Would you like to start a service [Y/N]?
if /I "%c%" EQU "Y" goto :1
if /I "%c%" EQU "N" goto :2
:1
set /p var= Service name:
:2
set /p c= Would you like to stop a service [Y/N]?
if /I "%c%" EQU "Y" goto :3
if /I "%c%" EQU "N" goto :4
:3
set /p var1= Service name:
:4
set /p c= Would you like to disable a service [Y/N]?
if /I "%c%" EQU "Y" goto :5
if /I "%c%" EQU "N" goto :6
:5
set /p var2= Service name:
:6
set /p c= Would you like to set a service to auto [Y/N]?
if /I "%c%" EQU "Y" goto :7
if /I "%c%" EQU "N" goto :10
:7
set /p var3= Service name:
:10
sc start %var%
sc stop %var1%
sc config %var2% start=disabled
sc config %var3% start=auto
Instead of checking codes, this works too
net start "Apache tomcat" || goto ExitError
:End
exit 0
:ExitError
echo An error has occurred while starting the tomcat services
exit 1
Using the return codes from net start and net stop seems like the best method to me. Try a look at this: Net Start return codes.
Syntax always gets me.... so...
Here is explicitly how to add a line to a batch file that will kill a remote service (on another machine) if you are an admin on both machines, run the .bat as an administrator, and the machines are on the same domain. The machine name follows the UNC format \myserver
sc \\ip.ip.ip.ip stop p4_1
In this case... p4_1 was both the Service Name and the Display Name, when you view the Properties for the service in Service Manager. You must use the Service Name.
For your Service Ops junkies... be sure to append your reason code and comment! i.e. '4' which equals 'Planned' and comment 'Stopping server for maintenance'
sc \\ip.ip.ip.ip stop p4_1 4 Stopping server for maintenance
We'd like to think that "net stop " will stop the service. Sadly, reality isn't that black and white. If the service takes a long time to stop, the command will return before the service has stopped. You won't know, though, unless you check errorlevel.
The solution seems to be to loop round looking for the state of the service until it is stopped, with a pause each time round the loop.
But then again...
I'm seeing the first service take a long time to stop, then the "net stop" for a subsequent service just appears to do nothing. Look at the service in the services manager, and its state is still "Started" - no change to "Stopping". Yet I can stop this second service manually using the SCM, and it stops in 3 or 4 seconds.
or you can start remote service with this cmd : sc \\<computer> start <service>
I just used Jonas' example above and created full list of 0 to 24 errorlevels. Other post is correct that net start and net stop only use errorlevel 0 for success and 2 for failure.
But this is what worked for me:
net stop postgresql-9.1
if %errorlevel% == 2 echo Access Denied - Could not stop service
if %errorlevel% == 0 echo Service stopped successfully
echo Errorlevel: %errorlevel%
Change stop to start and works in reverse.
Manual service restart is ok - services.msc has "Restart" button, but in command line both sc and net commands lacks a "restart" switch and if restart is scheduled in cmd/bat file, service is stopped and started immediately, sometimes it gets an error because service is not stopped yet, it needs some time to shut things down.
This may generate an error:
sc stop
sc start
It is a good idea to insert timeout, I use ping (it pings every 1 second):
sc stop
ping localhost -n 60
sc start
Here is the Windows 10 command to start System Restore using batch :
sc config swprv start= Auto
You may also like those commands :
Change registry value to auto start System restore
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore" /v DisableSR /t REG_DWORD /d 0 /f
Create a system restore point
Wmic.exe /Namespace:\root\default Path SystemRestore Call CreateRestorePoint "djibe saved your PC", 100, 12
Change System Restore disk usage
vssadmin resize shadowstorage /for=C: /on=C: /maxsize=10%
Enjoy
SC can do everything with services... start, stop, check, configure, and more...
Sometimes you can find the stop does not work..
My SQlServer sometimes does this. Using the following commandline kills it. If you really really need your script to kill stuff that doesn't stop. I would have it do this as a last resort
taskkill /pid [pid number] /f
SC
NET STOP/START
PsService
WMIC
Powershell is also easy for use option
SC and NET are already given as an anwests. PsService add some neat features but requires a download from Microsoft.
But my favorite way is with WMIC as the WQL syntax gives a powerful way to manage more than one service with one line (WMI objects can be also used through powershell/vbscript/jscript/c#).
The easiest way to use it:
wmic service MyService call StartService
wmic service MyService call StopService
And example with WQL
wmic service where "name like '%%32Time%%' and ErrorControl='Normal'" call StartService
This will start all services that have a name containing 32Time and have normal error control.
Here are the methods you can use.
With :
wmic service get /FORMAT:VALUE
you can see the available information about the services.
I am writing a windows service in C#, the stop/uninstall/build/install/start loop got too tiring. Wrote a mini script, called it reploy.bat and dropped in my Visual Studio output directory (one that has the built service executable) to automate the loop.
Just set these 3 vars
servicename : this shows up on the Windows Service control panel (services.msc)
slndir : folder (not the full path) containing your solution (.sln) file
binpath : full path (not the folder path) to the service executable from the build
NOTE: This needs to be run from the Visual Studio Developer Command Line for the msbuild command to work.
SET servicename="My Amazing Service"
SET slndir="C:dir\that\contains\sln\file"
SET binpath="C:path\to\service.exe"
SET currdir=%cd%
call net stop %servicename%
call sc delete %servicename%
cd %slndir%
call msbuild
cd %bindir%
call sc create %servicename% binpath=%binpath%
call net start %servicename%
cd %currdir%
Maybe this helps someone :)
I didn't find any of the answers above to offer a satisfactory solution so I wrote the following batch script...
:loop
net stop tomcat8
sc query tomcat8 | find "STOPPED"
if errorlevel 1 (
timeout 1
goto loop
)
:loop2
net start tomcat8
sc query tomcat8 | find "RUNNING"
if errorlevel 1 (
timeout 1
goto loop2
)
It keeps running net stop until the service status is STOPPED, only after the status is stopped does it run net start. If a service takes a long time to stop, net stop can terminate unsuccessfully. If for some reason the service does not start successfully, it will keep attempting to start the service until the state is RUNNING.
With this can start a service or program that need a service
#echo
taskkill /im service.exe /f
taskkill /im service.exe /f
set "reply=y"
set /p "reply=Restart service? [y|n]: "
if /i not "%reply%" == "y" goto :eof
cd "C:\Users\user\Desktop"
start service.lnk
sc start service
eof
exit