Start a Windows service from a batch script and take appropriate action based on result - windows

I have a .bat script that attempts to start a Windows service at the end.
:start_wildfly
echo.
set /p wildfly_service_name="Enter Wildfly service name: "
echo INFO: Starting %wildfly_service_name%...
echo.
call net start "%wildfly_service_name%"
I want to be able to interpret the result of the net start attempt so that I can have my script take the appropriate action if it fails (e.g. if the service is already running, restart it. If the service name is invalid, re-prompt for the name again, if the user doesn't have sufficient privileges, exit).
The problem is that the NET command does not return the documented Win32_Service class codes.
It does echo errors on the console, however:
The requested service has already been started.
More help is available by typing NET HELPMSG 2182.
See http://ss64.com/nt/net_service.html for a list of the errors.
Unforunately, the errorlevel variable is always 2 in these error cases, so I can't rely on that.
What I'm now trying to do is run a FIND on the output of the NET command, searching for specific error codes and act upon them.
net start Wildfly 2>&1 | FIND "2182"
if %errorlevel% equ 0 goto service_already_running
So, the result of the FIND is stored in errorlevel and I can check to see if the FIND succeeded by checking if errorlevel is 0. This works.
Now, the problem comes when I want to check for more than one error code. I don't know how to expand the code above to check for "2185" as well, for example, and goto a different label in that case.
I'm now attempting to store the entire result of the NET command into a variable, and then run a FINDSTR on that variable.
setlocal EnableDelayedExpansion
set "output_cnt=0"
for /F "delims=" %%f in ('dir /b') do (
set /a output_cnt+=1
set "output[!output_cnt!]=%%f"
)
for /L %%n in (1 1 !output_cnt!) DO echo !output[%%n]!
This should store and echo each line of the output, however the last line doesn't seem to do anything.
And then I've also found some code that should search within a variable and return whether or not that string was found:
echo.%output%|findstr /C:"2182" >nul 2>&1 && echo Found || echo Not found.
I've had no luck putting it all together though. I just want to be able to interpret the result of the NET START <SERVICE> and jump to certain labels based on the result.

I want to be able to interpret the result of the net start attempt
so that I can have my script take the appropriate action if it fails (e.g. if the service is already running, restart it. If the service name is invalid, re-prompt for the name again, if the user doesn't have sufficient privileges, exit).
Start the service as you are already doing:
net start "%wildfly_service_name%"
Now check the status of the service.
There are two ways to do this.
Use net start again to see if the service is running:
net start | find "%wildfly_service_name%" > nul
if errorlevel 1 echo The service is not running
Use sc (Service Control) to check the service status:
SC query %wildfly_service_name% | find "STATE" | find "STOPPED"
Or
sc query %wildfly_service_name% | find "STATE" | find "RUNNING"
The two statements above will return %errorlevel% = 1 if the text is not found.
Further Reading
An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
net - The NET Command is used to manage network resources.
sc - Service Control - Create, Start, Stop, Query or Delete any Windows SERVICE.

Taking DavidPostill's answer of using net start to check the status of the service, here is my new solution:
echo.
echo INFO: Starting %wildfly_service_name%...
echo.
:verify_not_running
net start | find "%wildfly_service_name%" > nul
if %errorlevel% equ 0 goto restart_wildfly
:start_wildfly
net start "%wildfly_service_name%"
goto verify_running
:restart_wildfly
echo The %wildfly_service_name% service is already running. Will now restart...
net stop "%wildfly_service_name%"
net start "%wildfly_service_name%"
:verify_running
net start | find "%wildfly_service_name%" > nul
if errorlevel 1 goto start_wildfly
This script will first verify the service is not running.
If the service is already running, it will restart the service.
In either case, I check at the end to make sure the service is now started. If not, repeat the process over again.
Note that I no longer have a requirement to check that the service name was valid. The service name is now hardcoded earlier in the script so it is assumed to be correct.
And to handle the case of insufficient privileges, I added this snippet at the beginning of the script:
:check_permissions
net session >nul 2>&1
if errorlevel 1 (
echo.
echo ERROR: This script must be run as an Administrator. Please re-run the script from an elevated command prompt.
echo.
echo Right-click "cmd.exe" from the Start menu and select "Run As Administrator".
exit /b %error_level%
)

You're right; the net command apparently always returns 2 for any kind of error. However, you can use the sc start command as a drop-in replacement for net start, and that one does indicate different errors through distinct exit statuses, in particular 1056 for An instance of the service is already running. So, you can use use
sc start "%wildfly_service_name%"
And then check %errorlevel% afterwards.

Related

Batch test if python.exe is running specific file

I am making a web controller for a python service, so that a user can start and stop the service. I need to be able to know whether the service is running.
I want to check whether python is running my script from cmd. echo 1 if it is running my script otherwise echo 0
such as:
if (python is running bot.py) (
echo 1
)
It is a bit tricky in plain cmd, but this seems to work:
#echo off
tasklist.exe /V /FI "IMAGENAME eq cmd.exe" /FO LIST | find "bot.py" >nul
if ERRORLEVEL 1 (
echo 0
) else (
echo 1
)
You would probably be best off having a file that is created by the running bots, which contains their PID, and then checking for the presence of this file. It would allow you to get the PID, but it does rely on the processes being terminated cleanly.
This works similarly to lock files, which can be used to stop 2 instances of a program running on the same data at the same time.

Windows batch file to connect to share and execute app

I have a batch file running on Windows 7 x86. I am trying to script a connection to a share and then once that is done to execute an app.
net use \\appserver001\mycompany.ptshare\OPS /user:geek xyz!## /persistent:yes
echo %errorlevel%
if errorlevel 2 goto message
if errorlevel 1 goto message
start "" "\\appserver001\mycompany.ptshare\OPS\OPSapp.exe"
echo %errorlevel%
if errorlevel 2 goto message
if errorlevel 1 goto message
goto end
:message
cls
echo ERROR IN CONNECTING TO SERVER
:end
The NET USE connection is made as the command window says "The command completed successfully". Then when it reaches the line to execute the app I get a pop-up message "Invalid location for program!".
I swear I have done his before but cant figure out why it will not run my app.
"Invalid location for program!" sounds like an error message that could come from OPSapp.exe itself. You could verify that by opening Task Manager and checking whether OPSapp is listed in the Processes tab when the error pops. If that's not the case then you may ignore the rest of this post.
Some programs require to be launched from a drive-letter based path (e.g. X:\etc\app.exe) rather than a UNC path (e.g. \\srv\etc\app.exe). Such a program can check at startup the location where it's been started from, then pop an error message and exit if it's a UNC path, instead of the drive-letter based one it expects.
The workaround in such cases is to (temporarily) map a drive letter to the network share, then use it to launch the program. For example, in your case replace
start "" "\\appserver001\mycompany.ptshare\OPS\OPSapp.exe"
with
pushd "\\appserver001\mycompany.ptshare\OPS"
start "" "OPSapp.exe"
If this still doesn't work, then it's possible that OPSapp expects more than just a drive-letter based path, perhaps a particular directory structure someplace, or registry entries etc - in other words it may not be portable enough to be simply runnable by path.

Batch file to check Windows services and Start them

I am trying to create a batch file that will sort 7 windows services into a list then check one by one if they're running, and if they aren't, start them.
What I have doesn't seem to be wokring and seems to echo set i=o. I am trying to find out how to properly execute the two for loops and if anybody has any suggestions for syntax that would be awesome
I was able to create a very primitive version but wanted to learn more about batch file "programming". This is what I've come up with so far:
::Enter in CC number
set /p CC=Enter The Site's CC:
#echo off
setlocal EnableDelayedExpansion
::Create vector with names of services
set i=0
for %%s in
("Apache Tomcat"
"OracleServicePD"
"OracleXETNSListener_bqw"
"System Audit Service"
"RPOS ScemComms Service"
"RPOS debit credit service"
"RPOS Remote Device Service"
"RPOS Messaging Service"
) do (
set /A i=i+1
set services[!i!]=%%s
)
::Check if all services are running, if not go to it's respective net start method
::After all is checked, it goes to :check to show services are running
set n=0
:loop
for /L %%G in (0,1,7) do (
net start | find !services[%n%]! > nul 2>&1
if not "%errorlevel%"=="0"
set pathname=!services[%n%]!
set /A n=n+1
goto %pathname%
)
goto check
:"Apache Tomcat"
net start tomcat6
goto loop
:"OracleServicePD"
net start "OracleServicePD%CC%"
goto loop
:"OracleXETNSListener_bqw"
net start "OracleXETNSListener_bqw"
goto loop
:"System Audit Service"
net start "System Audit Service"
goto loop
:"RPOS ScemComms Service"
net start "RPOS ScemComms Service"
goto loop
:"RPOS debit credit service"
net start "RPOS debit credit service"
goto loop
:"RPOS Remote Device Service"
net start "RPOS Remote Device Service"
goto loop
:"RPOS Messaging Service"
net start "RPOS Messaging Service"
goto loop
:check
echo Apache Tomcat && sc query tomcat6 | find "STATE"
echo OracleServicePD%CC% && sc query "OracleServicePD%CC%" | find "STATE"
echo OracleXETNSListener_bqw && sc query "OracleXETNSListener_bqw" | find "STATE"
echo System Audit Service && sc query "System Audit Service" | find "STATE"
echo RPOS ScemComms Service && sc query "RPOS ScemComms Service" | find "STATE"
echo RPOS debit credit service && sc query "RPOS debit credit service" | find "STATE"
echo RPOS Remote Device Service && sc query "RPOS Remote Device Service" | find "STATE"
echo RPOS Messaging Service && sc query "RPOS Messaging Service" | find "STATE"
first, your first service is services[1], but your loop starts with 0.
more importantly, where does %n% come from? you mean %%G here.
sc start AeLookupSvc&&echo Started||(sc start AeLookupSvc|Findstr /c:"1056"&&Echo Already Running||Echo Error starting service)
Your pattern of testing then doing is not a good programming technique. You do and test if it worked.
The above does one service and reports if already running, if it was started, or what error prevents it starting. All in one line.
From MSDos 6.22 Help File.
│The following list shows each exit code and a brief description of its
│meaning:
│
│0
│ The search was completed successfully and at least one match was found.
│
│1
│ The search was completed successfully, but no matches were found.
│
│2
│ The search was not completed successfully. In this case, an error
│ occurred during the search, and FIND cannot report whether any matches
│ were found.
│
│You can use the ERRORLEVEL parameter on the command line in a batch
│program to process exit codes returned by FIND.
A list of command line things.
& seperates commands on a line.
&& executes this command only if previous command's errorlevel is 0.
|| (not used above) executes this command only if previous command's errorlevel is NOT 0
> output to a file
>> append output to a file
< input from a file
| output of one command into the input of another command
^ escapes any of the above, including itself, if needed to be passed to a program
" parameters with spaces must be enclosed in quotes
+ used with copy to concatinate files. E.G. copy file1+file2 newfile
, used with copy to indicate missing parameters. This updates the files modified date. E.G. copy /b file1,,
%variablename% a inbuilt or user set environmental variable
!variablename! a user set environmental variable expanded at execution time, turned with SelLocal EnableDelayedExpansion command
%<number> (%1) the nth command line parameter passed to a batch file. %0 is the batchfile's name.
%* (%*) the entire command line.
%<a letter> or %%<a letter> (%A or %%A) the variable in a for loop. Single % sign at command prompt and double % sign in a batch file.
.

Batch file to uninstall a program

I'm trying to uninstall a program EXE via batch file and am not having any success.
The uninstall string found in the registry is as follows:
C:\PROGRA~1\Kofax\Capture\ACUnInst.exe /Workstation
C:\PROGRA~1\Kofax\Capture\UNWISE.EXE /U
C:\PROGRA~1\Kofax\Capture\INSTALL.LOG
If I run that from CMD or batch it does nothing.
If I run C:\PROGRA~1\Kofax\Capture\UNWISE.EXE /U from CMD it will open up a dialog box to point to the INSTALL.LOG file and then proceed to uninstall.
At the end, it will ask me to click finish.
I need this to be silent, can you point me in the right direction? This is on XP and 7.
Every program that properly installs itself according to Microsoft's guidelines makes a registry entry in either HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall (for machine installs) or HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall (for user profile installs). Usually, the key for the program will be its GUID, or else the name of the program. Within that key will be an entry called UninstallString. This contains the command to execute to uninstall the program.
If you already know ahead of time what you will be uninstalling, it should be easy enough to just put that in your batch file. It gets tricky when you try to automate that process though. You can use the reg command to get data from the registry, but it returns a lot of text around the actual value of a given key, making it hard to use. You may want to experiment with using VBscript or PowerShell, as they have better options for getting data from the registry into a variable.
This might help you further.....
How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit
I've had the same problem and this is what I came up with.
Before you start using this method though, you might wanna look up the name of the application on WMIC using CMD so..
First you wanna do: WMIC product > C:\Users\"currentuser"\Desktop\allapps.txt
I'd recommend to output the command to an TXT file because it's really confusing to read it in the Cmd prompt, plus is easier to find the data you are looking for.
Now what you wanna do is find the actual name of the app... If you look at the code I put in, the app name says SkypeT because skype has "™" in the end of it and the command prompt can't interpretate that as it is.
After you got the app name, just put in the find in the 4th line and substitute, a few lines which contain my examples with skype...
Also you can probably creat a variable called %APP% and not worry as much, but at it's current it works just fine...
One thing to note! with me the msi /quiet command did not work, the program would not install or uninstall so I used /passive, which lets the users see what's going on.
#Echo off
CD %cd%
:VerInstall
for /f "tokens=12,*" %%a in ('wmic product list system ^| Find /I "SkypeT"') do (
if Errorlevel = 0 (
Echo Skype is installed! )
if Errorlevel = 1 ( Echo Skype is not installed, proceding to the installation!
Ping localhost -n 7 >nul
goto :Reinstall )
)
:Status
tasklist /nh /fi "IMAGENAME eq "APP.exe" | find ":"> nul
if errorlevel = 1 goto :force
goto :Uninstall
:Force
echo We are killing the proccess... Please do not use the application during this process!
Ping localhost -n 7 > nul
taskkill /F /FI "STATUS eq RUNNING" /IM APP* /T
echo The task was killed with success! Uninstalling...
Ping localhost -n 7 > nul
:Uninstall
cls
for /f "tokens=12,*" %%a in ('wmic product list system ^| Find /I "SkypeT"') do (
set %%a=%%a: =%
msiexec.exe /x %%a /passive /norestart
)
:DoWhile
cls
Tasklist /fi "IMAGENAME eq msi*" /fi "STATUS eq RUNNING" | Find ":" >nul
if errorlevel = 1 (
echo Installation in progress
Goto :DoWhile
)
echo Skype is Uninstalled
:Reinstall
msiexec.exe /i SkypeSetup.msi /passive /norestart
:reinstallLoop
Tasklist /fi "IMAGENAME eq msi*" /fi "STATUS eq RUNNING" | Find ":" >nul
if errorlevel = 1 (
echo Installation in progress
goto :reinstallLoop
)
echo Skype is installed
:end
cls
color 0A
Echo Done!
exit
One last thing. I used this as an Invisible EXE task, so the user couldn't interact with the command prompt and eventually close the window (I know, I know, it makes the whole echoes stupid, but it was for testing purposes).for that I used BAT to EXE converter 2.3.1, you can put everything to work on the background and it will work very nicelly. if you want to show progress to users just write START Echo "info" and replace the info with whatever you want, it will open another prompt and show the info you need.
Remember, Wmic commands sometimes take up to 20 seconds to execute since it's querying the conputer's system, so it might look like it's doing nothing at first but it will run! ;)
Good luck :)
We needed a batch file to remove a program and we couldn't use programmatic access to the registry.
For us, we needed to remove a custom MSI with a unique name. This only works for installers that use msi or integrate such that their cached installer is placed in the Package_Cache folder. It also requires a unique, known name for the msi or exe. That said, it is useful for those cases.
dir/s/b/x "c:\programdata\packag~1\your-installer.msi" > removeIt.bat
set /p RemoveIt=< removeIt.bat
echo ^"%RemoveIt%^" /quiet /uninstall > removeIt.bat
removeIt.bat
This works by writing all paths for 'your-installer.msi' to the new file 'removeIt.bat'
It then assigns the first line of that bat file to the variable 'RemoveIt'
Next, it creates a new 'removeIt.bat' that contains the path/name of the .msi to remove along with the needed switches to do so.
Finally, it runs the batch file which executes the command to uninstall the msi. This could be done with an .exe as well.
You will probably want to place the 'removeIt.bat' file into a known writable location, for us that was the temp folder.

Stop and Start a service via batch or cmd file?

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

Resources