Windows 批处理文件根据邮件正文中的条件发送带有文件名的电子邮件

Windows 批处理文件根据邮件正文中的条件发送带有文件名的电子邮件

目前我在 Win 7 中有一个 .bat 文件,其中包含以下内容:

@echo on
setlocal EnableDelayedExpansion
set "[email protected]"
set "emailPassword=x"
set "[email protected]"
set "subject=File Changed"
FOR %%G IN ("D:\") DO attrib -A "%%G"
set "body="
FOR %%G IN ("D:\") DO (
    attrib "%%G" | forfiles /P D:\ /m * /d -1 
    )
if not "%body%"=="" echo sending email
if not "%body%"=="" set "body=The following files  @echo %a have been changed:!body!"
if not "%body%"=="" powershell.exe -command "Send-MailMessage -From '!emailUserName!' -to '!target!' -Subject '!subject!' -Body '!body!' -BodyAsHtml -SmtpServer 'smtp.gmail.com' -port '587' -UseSsl -Credential (New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ('!emailUserName!', (ConvertTo-SecureString -String '!emailPassword!' -AsPlainText -Force)))"

PAUSE

在上面的代码中,主要问题是我无法将以下代码的输出放入电子邮件正文或作为附件:

forfiles /P D:\ /m * /d -1 

上面的代码只是列出了文件名,cmd但我需要将这些文件名列表发送到第一个代码中的电子邮件正文中。对此有什么建议吗?

答案1

您可以将整个代码包装在 powershell 中:

@echo off
attrib -A "D:\"
powershell.exe -command "& {$body = forfiles /P D:\ /m * /d -1; $emailUserName = 'Email address'; $emailPassword = 'Password'; $target = 'Recipient Mail'; $subject = 'File changed'; Send-MailMessage -From "$emailUserName" -to "$target" -Subject "$Subject" -Body "$Body" -BodyAsHtml -SmtpServer 'smtp.gmail.com' -port '587' -UseSsl -Credential (New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ("$emailUserName", (ConvertTo-SecureString -String "$emailPassword" -AsPlainText -Force)))}"

相关内容