Command Prompt Stop, Wait, Start - cmd

I would like a simple batch while that does the following
Stops a Service
Wait 3 minutes
Starts the Service
so I have
net stopMitral Tasks Service
net startMitral Tasks Service
timeout /t 180
net stopMitral Tasks Service
net startMitral Tasks Service
Would this work?
In terms of the Net stopService
is that all that is need - no file path to the actual .exe?

This will stop and then restart the service listed, wait 180 seconds and then repeat it.
net stop "Mitral Tasks Service"
net start "Mitral Tasks Service"
timeout /t 180 /nobreak
net stop "Mitral Tasks Service"
net start "Mitral Tasks Service"

Related

Run .bat as administrator without manual confirmation

I want my .bat file to always run as administrator without me having to manually allow it to make changes to my device each time. It's part of a larger automated process and simply clears and resets the clipboard. Since it's automated I can't be there each time to hit yes.
wmic service where "name like '%%cbdhsvc_%%'" call stopservice
%windir%\System32\cmd.exe /c "echo off | clip"
wmic service where "name like '%%cbdhsvc_%%'" call startservice
Alternatively is there a way I could set it to run say every 5 seconds in the background with only a single confirmation until I tell it to stop or for a set period? Thanks
For only having to allow administrator once, you could use the timeout command.
:top
"code"
timeout /t 5 /NOBREAK > nul
goto :top
do timeout/? in cmd to see the usage.

Shut down machine after being idle with batch file?

I don't even know if this is possible, but is there anyway to shut down a machine after (n) minutes, using a batch file?
Currently I already have a batch file which works alongside ranorex and a virtual machine, and I need the machine to shut itself down after it has been idle for 10 minutes or so, just to give everything else in the batch file plenty of time to run. Is there any way of doing this?
Just use the command for shutdown and add the option for the time to wait:
shutdown /s /t 600 /f
/s is for shutting down the computer
/t is for wait before do the operation with time in seconds (10*60=600)
/f is for forcefully close all applications
With shutdown /a you can abort the action befor the time runs off. For more options use the help of the shutdown-command.

Batch file won`t start program when launched from windows service

I have created a batch file to run when a specific service stops.
The batch file should stop the relevant software running, restart some services (stop / start) and start the software again.
It`s a simple code:
#echo off
Taskkill /F /IM program1.exe
Taskkill /F /IM program2.exe
timeout /t 5
net stop service1
net stop service2 && net start service2
net start service3
timeout /t 2
start C:/path/program1.exe
start C:/path/program2.exe
Have set the service up to run the batch file as recovery at first failure.
Batch file is linked via a shortcut to be able to run it as administrator.
This works perfectly when running the batch file directly, but when it`s executed by the service recovery, the start-up of the software fails.
Does anyone have any idea what could be wrong?
In some circumstances timeout /t 5 might cause trouble. Try to replace it with PING -n 6 127.0.0.1 > NUL.

Stop/Start Service - Handling STOP_PENDING and START_PENDING

How do you make your stop/start service scripts gracefully handling the services that get stuck in STOP_PENDING or START_PENDING...
Related with SC STOP and START. Stop and Start a service via batch or cmd file?
I have one aproach in mind, but I don't like it.
This is the way i'm approaching the stop.
Stop: sc %host% stop %service% || ECHO ERROR! && EXIT -1
Loop waiting for state to be STOPPED.
Loop with a maximum number of iterations (e.g. 30). Testing if service is stopped (e.g. sc %host% query %service% | find /i "STOPPED"). Wait some seconds in each iteration (e.g. 10). Reaching the maximum iterations, try to kill the process using taskkill (e.g. work the output of sc queryex Alerter | find /i "PID").
First open service.msc, in the properties dialog for your targeted service go to the Recovery Tab *(run -> services.msc -> right-click Target-Service -> Properties -> Recovery tab*)
Make sure the First\Second\Subsequent failures are all set to : Take No Action.
Get the PID of your target service using: sc queryex ServiceName:
Kill the process using taskkill /f /pid your_PID_number
For me sometimes a 'Windows service' is hanging when I have the window services.msc open. I can't kill the process, neither use net stop or sc stop.
But when I close the services.msc window, the service immediately stops.

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