我想编写一个执行以下操作的批处理文件:
- 检查服务是否正在运行
- 如果正在运行,请退出该批处理
- 如果未运行,请启动服务
到目前为止,我在Google上搜索过的代码示例都无法正常工作,因此我决定不发布它们。
通过以下方式启动服务:
net start "SERVICENAME"
- 如何检查服务是否正在运行,以及如何在批处理文件中创建if语句?
- 我有点困惑。我必须传递给网络起点的论点是什么?服务名称或其显示名称?
我想编写一个执行以下操作的批处理文件:
到目前为止,我在Google上搜索过的代码示例都无法正常工作,因此我决定不发布它们。
通过以下方式启动服务:
net start "SERVICENAME"
Answers:
要检查服务的状态,请使用sc query <SERVICE_NAME>
。对于批处理文件中的if块,请查阅文档。
以下代码将检查服务的状态,如果服务MyServiceName
未运行则将其启动(如果服务未运行,则将执行if块):
for /F "tokens=3 delims=: " %%H in ('sc query "MyServiceName" ^| findstr " STATE"') do (
if /I "%%H" NEQ "RUNNING" (
REM Put your code you want to execute here
REM For example, the following line
net start "MyServiceName"
)
)
其作用说明:
至于第二个问题,您要传递给的参数net start
是服务名称,而不是显示名称。
sc query "SCardSvr"
?
要切换服务,请使用以下内容;
NET START“分布式事务处理协调器” || NET STOP“分布式事务处理协调器”
||
实际上是一个OR
运营商,尽管在这种情况下,它在功能上的ELSE
发言。这是一个细微但重要的区别。仍然得到+1-我一直在Unix / Linux shell脚本中这样做,不知道为什么我从没想过要在Windows批处理中这样做。
您可以使用以下命令查看服务是否正在运行:
sc query [ServiceName] | findstr /i "STATE"
当我为NOD32 Antivirus运行它时,我得到:
STATE : 4 RUNNING
如果停止,我将得到:
STATE : 1 STOPPED
您可以在变量中使用它,然后确定是否使用NET START。
服务名称应该是服务名称,而不是显示名称。
应该这样做:
FOR %%a IN (%Svcs%) DO (SC query %%a | FIND /i "RUNNING"
IF ERRORLEVEL 1 SC start %%a)
语言独立版本。
@Echo Off
Set ServiceName=Jenkins
SC queryex "%ServiceName%"|Find "STATE"|Find /v "RUNNING">Nul&&(
echo %ServiceName% not running
echo Start %ServiceName%
Net start "%ServiceName%">nul||(
Echo "%ServiceName%" wont start
exit /b 1
)
echo "%ServiceName%" started
exit /b 0
)||(
echo "%ServiceName%" working
exit /b 0
)
Set ServiceName=Jenkins
为Set ServiceName=%~1
并称呼它即可watch-service.bat "Jenkins"
我只是找到了该线程,并且如果该人员不想使用批处理文件来重新启动服务,则想添加到讨论中。在Windows中,如果您转到服务,服务属性,然后进行恢复,则有一个选项。您可以在此处设置服务的参数。喜欢在服务停止时重新启动服务。另外,您甚至可以再次尝试失败,做一些与重新启动计算机不同的操作。
cuando se使用Windows enEspañol,elcódigodebe quedar asi(使用西班牙语的Windows时,代码为):
for /F "tokens=3 delims=: " %%H in ('sc query MYSERVICE ^| findstr " ESTADO"') do (
if /I "%%H" NEQ "RUNNING" (
REM Put your code you want to execute here
REM For example, the following line
net start MYSERVICE
)
)
Reemplazar MYSERVICE服务于海上维修服务。维也纳市政总局。(将MYSERVICE替换为要处理的服务的名称。您可以在服务属性上看到服务的名称。)
对于Windows Server 2012,以下对我有用。仅将“ SERVICENAME”替换为实际的服务名称:
@ECHO OFF
SET SvcName=SERVICENAME
SC QUERYEX "%SvcName%" | FIND "STATE" | FIND /v "RUNNING" > NUL && (
ECHO %SvcName% is not running
ECHO START %SvcName%
NET START "%SvcName%" > NUL || (
ECHO "%SvcName%" wont start
EXIT /B 1
)
ECHO "%SvcName%" is started
EXIT /B 0
) || (
ECHO "%SvcName%" is running
EXIT /B 0
)
如果该服务是以这种方式启动的,我还希望发送一封电子邮件,因此在@Ic代码中添加了一些内容,只是以为我可以将其发布,以防它对任何人有所帮助。我使用了SendMail,但还有其他命令行选项如何从Windows批处理文件发送简单的电子邮件?
set service=MyServiceName
for /F "tokens=3 delims=: " %%H in ('sc query %service% ^| findstr " STATE"') do (
if /I "%%H" NEQ "RUNNING" (
net start %service%
for /F "tokens=3 delims=: " %%H in ('sc query %service% ^| findstr " STATE"') do (
if /I "%%H" EQ "RUNNING" (
SendMail /smtpserver localhost /to me@mydomain.com /from watchdog@mydomain.com /subject Service Autostart Notification /body Autostart on service %service% succeded.
) else (
SendMail /smtpserver localhost /to me@mydomain.com /from watchdog@mydomain.com /subject Service Autostart Notification /body Autostart on service %service% failed.
)
)
)
)
使用Powershell脚本启动服务。您可以将其链接到任务计划程序,并按时间间隔或根据需要触发它。将其创建为PS1文件,即扩展名为PS1的文件,然后从任务计划程序中触发此文件。
开始停止服务
在任务计划程序中,如果要在服务器上使用它,则在参数中使用此
-noprofile -executionpolicy旁路-file“ C:\ Service Restart Scripts \ StopService.PS1”
通过在cmd上运行相同命令进行验证(如果可行),它也应在任务计划程序上运行
$Password = "Enter_Your_Password"
$UserAccount = "Enter_Your_AccountInfor"
$MachineName = "Enter_Your_Machine_Name"
$ServiceList = @("test.SocketService","test.WcfServices","testDesktopService","testService")
$PasswordSecure = $Password | ConvertTo-SecureString -AsPlainText -Force
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $UserAccount, $PasswordSecure
$LogStartTime = Get-Date -Format "MM-dd-yyyy hh:mm:ss tt"
$FileDateTimeStamp = Get-Date -Format "MM-dd-yyyy_hh"
$LogFileName = "C:\Users\krakhil\Desktop\Powershell\Logs\StartService_$FileDateTimeStamp.txt"
#code to start the service
"`n####################################################################" > $LogFileName
"####################################################################" >> $LogFileName
"###################### STARTING SERVICE ##########################" >> $LogFileName
for($i=0;$i -le 3; $i++)
{
"`n`n" >> $LogFileName
$ServiceName = $ServiceList[$i]
"$LogStartTime => Service Name: $ServiceName" >> $LogFileName
Write-Output "`n####################################"
Write-Output "Starting Service - " $ServiceList[$i]
"$LogStartTime => Starting Service: $ServiceName" >> $LogFileName
Start-Service $ServiceList[$i]
$ServiceState = Get-Service | Where-Object {$_.Name -eq $ServiceList[$i]}
if($ServiceState.Status -eq "Running")
{
"$LogStartTime => Started Service Successfully: $ServiceName" >> $LogFileName
Write-Host "`n Service " $ServiceList[$i] " Started Successfully"
}
else
{
"$LogStartTime => Unable to Stop Service: $ServiceName" >> $LogFileName
Write-Output "`n Service didn't Start. Current State is - "
Write-Host $ServiceState.Status
}
}
#code to stop the service
"`n####################################################################" > $LogFileName
"####################################################################" >> $LogFileName
"###################### STOPPING SERVICE ##########################" >> $LogFileName
for($i=0;$i -le 3; $i++)
{
"`n`n" >> $LogFileName
$ServiceName = $ServiceList[$i]
"$LogStartTime => Service Name: $ServiceName" >> $LogFileName
Write-Output "`n####################################"
Write-Output "Stopping Service - " $ServiceList[$i]
"$LogStartTime => Stopping Service: $ServiceName" >> $LogFileName
Stop-Service $ServiceList[$i]
$ServiceState = Get-Service | Where-Object {$_.Name -eq $ServiceList[$i]}
if($ServiceState.Status -eq "Stopped")
{
"$LogStartTime => Stopped Service Successfully: $ServiceName" >> $LogFileName
Write-Host "`n Service " $ServiceList[$i] " Stopped Successfully"
}
else
{
"$LogStartTime => Unable to Stop Service: $ServiceName" >> $LogFileName
Write-Output "`nService didn't Stop. Current State is - "
Write-Host $ServiceState.Status
}
}
@Echo off
Set ServiceName=wampapache64
SC queryex "%ServiceName%"|Find "STATE"|Find /v "RUNNING">Nul&&(
echo %ServiceName% not running
echo
Net start "%ServiceName%"
SC queryex "%ServiceName%"|Find "STATE"|Find /v "RUNNING">Nul&&(
Echo "%ServiceName%" wont start
)
echo "%ServiceName%" started
)||(
echo "%ServiceName%" was working and stopping
echo
Net stop "%ServiceName%"
)
pause
与@DanielSerrano的答案相关,最近我对sc.exe
命令的本地化(即西班牙语)感到有些困惑。我的建议是查明保存数字服务状态的行和令牌并对其进行解释,这应该更加健壮:
@echo off
rem TODO: change to the desired service name
set TARGET_SERVICE=w32time
set SERVICE_STATE=
rem Surgically target third line, as some locales (such as Spanish) translated the utility's output
for /F "skip=3 tokens=3" %%i in ('""%windir%\system32\sc.exe" query "%TARGET_SERVICE%" 2>nul"') do (
if not defined SERVICE_STATE set SERVICE_STATE=%%i
)
rem Process result
if not defined SERVICE_STATE (
echo ERROR: could not obtain service state!
) else (
rem NOTE: values correspond to "SERVICE_STATUS.dwCurrentState"
rem https://msdn.microsoft.com/en-us/library/windows/desktop/ms685996(v=vs.85).aspx
if not %SERVICE_STATE%==4 (
echo WARNING: service is not running
rem TODO: perform desired operation
rem net start "%TARGET_SERVICE%"
) else (
echo INFORMATION: service is running
)
)
经过测试: