email - 释放 send-mailmessage 出错时留下的文件锁

标签 email powershell powershell-2.0 filelock

我正在使用 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 设置为“停止”,那么日志文件上的文件锁不会被释放。如果 erroraction 设置为“停止”,则会释放日志文件,但不会触发 Catch block 。

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

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

最佳答案

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

使用 PowerShell 1 方法通过电子邮件发送文件副本或创建您自己的电子邮件功能(一个示例:how to send an email with attachement using powershell v1?)

关于email - 释放 send-mailmessage 出错时留下的文件锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18598770/

相关文章:

powershell - Powershell-NewItemUnauthorizedAccessError

powershell - 如何使用 PowerShell 将 UTC 转换为 EST

matlab - 通过 MATLAB 发送电子邮件

来自 mysql 的 php 邮件模板变量

powershell - 调用-Sqlcmd错误: Login failed for user xxxx when running powershell to call remote DB server

xml - 如何将 Invoke-RestMethod 的响应转换为 XML?

html - 内容上的电子邮件 HTML 边框,而不是单元格?

sql-server - SQL Server : send email

perl - 在Perl或PowerShell中使用增量文件更新记录