我正在使用 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
是否有我应该运行的命令来释放锁,或者这是一个错误,还是我以错误的方式解决这个问题?
最佳答案
使用 PowerShell 1 方法通过电子邮件发送文件副本或创建您自己的电子邮件功能(一个示例:how to send an email with attachement using powershell v1?)
关于email - 释放 send-mailmessage 出错时留下的文件锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18598770/