3

我正在使用 Send-MailMessage cmdlet 发送日志文件的副本。但是,我想在日志文件中添加一行以发送状态。

代码:

$To = "toaddress@email.com"
$Subject = "Test Email Attachment"
$From = "fromaddress@email.com"
$Body = "Please find log file attached"
$SMTPServer = "smtp.server.com"
$LogFile = "Testlog.log"

Add-Content -Path $LogFile -Value "Trying to email log..."
Try
    {
        send-mailmessage -to $To -subject $Subject -From $From -body $Body -smtpserver $SMTPServer -attachments $LogFile -ErrorAction Stop
        Add-Content -Path $LogFile -Value "Successfully emailed log to: $To"
    }
Catch [system.exception]
    {
        Add-Content -Path $LogFile -Value "Error emailing log to: $To"
    }
Finally {}

错误:

PS E:\> . .\TestMail.ps1
Add-Content : The process cannot access the file 'E:\Testlog.log' because it is being used by another process.
At E:\TestMail.ps1:16 char:14
+         Add-Content <<<<  -Path $LogFile -Value "Error emailing log to: $To"
    + CategoryInfo          : WriteError: (E:\Testlog.log:String) [Add-Content], IOException
    + FullyQualifiedErrorId : GetContentWriterIOError,Microsoft.PowerShell.Commands.AddContentCommand

如果电子邮件成功,这可以正常工作,但如果失败(例如 smtp 服务器不可用),并且错误操作设置为“停止”,则不会释放日志文件上的文件锁定。如果 erroraction设置为“Stop”,则日志文件将被释放,但不会触发 Catch 块。

如果您正在滚动自己的邮件功能,我找到了对“dispose”方法的引用,但我不确定它如何与 Send-MailMessage cmdlet 一起使用:http: //petermorrissey.blogspot.com.au/ 2013/01/sending-email-messages-with-powershell.html

是否有我应该运行的命令来释放锁,或者这是一个错误,还是我以错误的方式解决这个问题?

4

1 回答 1

1

似乎是一个错误:https ://connect.microsoft.com/PowerShell/feedback/details/785417/out-file-cannot-access-logfile-references-in-attachments-of-failed-send-mailmessage-call

通过电子邮件发送文件副本或使用 PowerShell 1 方法创建自己的电子邮件功能(一个示例:如何使用 powershell v1 发送带有附件的电子邮件?

于 2013-09-09T04:38:03.207 回答