批处理脚本以启动特定的服务集

时间:2019-02-06 07:51:52

标签: batch-file scripting

批处理脚本失败。语法不正确。如果服务没有运行,请启动它们,并在启动时触发电子邮件。

for /f "tokens=1*" %%a in ('
sc queryex state^= all ^| findstr /r /c:"DISPLAY_NAME: .*Sm" get state^| 
Find /v "RUNNING"')
do net start "%%b"

[编辑]

您能告诉我我要去哪里了吗...我正在检查非活动服务并在启动时启动它们,我正在生成电子邮件警报。但是它会循环播放并返回n个邮件。我个人需要终止该过程...如果该服务正在运行,那么我也将收到一封电子邮件。

setlocal

:loop
@for /f "tokens=1*" %%a in ('sc queryex state^=inactive ^| findstr /r /c:"DISPLAY_NAME:.*ASP"') do net start "%%b" && goto :mail 

:mail
set Port=25
set SSL=False
set From="abc@gmail.com"
set To="abc@gmail.com"
set Subject="Subject line"
set Body="Email Body in one line"
set SMTPServer="smtp.gmail.com"
set User="abc@gmail.com"
set Pass="1234567"


if "%~7" NEQ "" (
set From="%~1"
set To="%~2"
set Subject="%~3"
set Body="%~4"
set SMTPServer="%~5"
set User="%~6"
set Pass="%~7"
set fileattach="%~8"
)

set "vbsfile=%temp%\email-bat.vbs"
del "%vbsfile%" 2>nul
set cdoSchema=http://schemas.microsoft.com/cdo/configuration
echo >>"%vbsfile%" Set objArgs       = WScript.Arguments
echo >>"%vbsfile%" Set objEmail      = CreateObject("CDO.Message")
echo >>"%vbsfile%" objEmail.From     = %From%
echo >>"%vbsfile%" objEmail.To       = %To%
echo >>"%vbsfile%" objEmail.Subject  = %Subject%
echo >>"%vbsfile%" objEmail.Textbody = %body%
if exist %fileattach% echo >>"%vbsfile%" objEmail.AddAttachment %fileattach%
echo >>"%vbsfile%" with objEmail.Configuration.Fields
echo >>"%vbsfile%"  .Item ("%cdoSchema%/sendusing")        = 2 ' not local, smtp
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpserver")       = %SMTPServer%
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpserverport")   = %port%
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpauthenticate") = 1 ' cdobasic
echo >>"%vbsfile%"  .Item ("%cdoSchema%/sendusername")     = %user%
echo >>"%vbsfile%"  .Item ("%cdoSchema%/sendpassword")     = %pass%
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpusessl")       = %SSL%
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpconnectiontimeout") = 30
echo >>"%vbsfile%"  .Update
echo >>"%vbsfile%" end with
echo >>"%vbsfile%" objEmail.Send

cscript.exe /nologo "%vbsfile%"

echo email sent (if variables were correct)
del "%vbsfile%" 2>nul
goto :loop

1 个答案:

答案 0 :(得分:0)

代替获取所有服务并尝试查找它们是否正在运行,而是直接从查询中获取inactive状态,然后从那里启动它:

@for /f "tokens=1*" %%a in ('sc queryex state^=inactive ^| findstr /r /c:"DISPLAY_NAME:.*Sm"') do (
    net start "%%b"
)

请注意,上述代码纯粹是为了提高可读性而使用括号,但并非必须如此,您可以按照以下方式在一行中全部复制:

@for /f "tokens=1*" %%a in ('sc queryex state^=inactive ^| findstr /r /c:"DISPLAY_NAME:.*Sm"') do net start "%%b"