验证(errorlevel)批处理脚本命令并使用其输出发送邮件

时间:2018-06-04 14:08:00

标签: windows powershell batch-file

我有更多批处理文件(cmd),如下所示,即执行一些命令并将错误级别代码的输出打印到文件中,然后使用该文件的输出向我发送电子邮件:

@echo off

set RESEXE1=0
set RESEXE2=0

SET MyPath=D:\test\client
SET PATH=%MyPath%\;%PATH%
SET PATH=%MyPath%\schema;%PATH%
SET PATH=%MyPath%\xml;%PATH%
SET PATH=%MyPath%\xsl;%PATH%
SET PATH=%MyPath%\DashboardPlugins;%PATH%

:BEGIN

cd /d %MyPath%

set RESEXE1=%ERRORLEVEL%
echo RESEXE1 : %RESEXE1% > D:\Temp\logs\test.txt

START "test" /MIN test.exe -UEOD /ccu:file:test2.config /pcu:file:D:\scripts\test.config /p:Common/Log/Path=D:\Misys\logs\batch\test /p:Common/Log/Verbosity=Warning -S'Report Processing':":0 

set RESEXE2=%ERRORLEVEL%
echo RESEXE2 : %RESEXE2% >> D:\Temp\logs\test.txt

:ENDBATCH

if %RESEXE1% == 0 set RESEXE=0

if %RESEXE1% NEQ 0 set RESEXE=1

if %RESEXE2% == 0 set RESEXE=0

if %RESEXE2% NEQ 0 set RESEXE=1

echo RESEXE : %RESEXE% >> D:\Temp\logs\test.txt

echo %~n0%~x0 >> D:\Temp\logs\test.txt

IF %RESEXE% NEQ 0  Powershell.exe -executionpolicy remotesigned -File D:\Temp\aaa.ps1

第二部分是我的sendmail脚本:

$From = "them@test.com"
$To = "me@test.com"
#$Cc = "he@test.com"
$Subject = $scname
$Body = Get-Content -Path D:\Temp\logs\test.txt
#$Attachments = D:\Temp\test.txt
$SMTPServer = "test.com"
$SMTPPort = "25"
Send-MailMessage -From $From -to $To -Subject "[test][test] $Subject" -Body  ($body | Out-String) -SmtpServer $SMTPServer -port $SMTPPort –DeliveryNotificationOption OnSuccess

我的问题是,我如何在批处理(cmd)脚本上为每个输出文件(例如:test.txt)声明一个动态变量,该文件是使用错误代码和其他信息生成的,并在sendmail的$ body变量中使用它脚本以输出电子邮件中的内容。

1 个答案:

答案 0 :(得分:0)

批处理文件:

@echo off

set RESEXE1=0
set scname=%~n0%~x0
set scname2=%~n0.txt
set pathlog=D:\Temp\logs
set pathfilelog=%pathlog%\%scname2%

:BEGIN

cd h: > %pathfilelog% 2>&1

set RESEXE1=%ERRORLEVEL%
echo RESEXE1 : %RESEXE1% >> %pathfilelog%

:ENDBATCH

 if %RESEXE1% == 0 set RESEXE=0

 if %RESEXE1% NEQ 0 set RESEXE=1

echo RESEXE : %RESEXE% >> %pathfilelog%

 echo %~n0%~x0 >> %pathfilelog%

 IF %RESEXE% NEQ 0  Powershell.exe -executionpolicy remotesigned -File D:\Temp\aaa.ps1 "%scname%" "%scname2%" "%pathfilelog%"

邮件脚本文件:

$scname=$args[0] 
$scname2=$args[1]
$pathfilelog=$args[2]  

$From = "test@test.com"
$To = "test@test.com"
#$Cc = "test@test.com"
$Subject = $scname
$Body = Get-Content -Path $pathfilelog
#$Attachments = D:\Temp\test.txt
$SMTPServer = "test.test.com"
$SMTPPort = "25"
Send-MailMessage -From $From -to $To -Subject "[test][test] $Subject - Failed" -Body  ($body | Out-String) -SmtpServer $SMTPServer -port $SMTPPort –DeliveryNotificationOption OnSuccess

这解决了我的问题,他们。