我使用Send-MailMessage cmdlet发送日志文件的副本。但是,我想在日志文件中添加一行,其状态为Send。
代码:
$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服务器不可用),并且错误被设置为&#34;停止&#34;,那么日志文件上的文件锁定就没有了。得到释放。如果错误 设置为&#34;停止&#34;,则会释放日志文件,但Catch块不会被触发。
我找到了对#34; dispose&#34;的引用。如果您正在滚动自己的邮件功能,但我不确定它如何与Send-MailMessage cmdlet一起使用:http://petermorrissey.blogspot.com.au/2013/01/sending-email-messages-with-powershell.html
我是否应该运行一个命令来释放锁定,或者这是一个错误,还是我以错误的方式解决这个问题?
答案 0 :(得分:1)
使用PowerShell 1方法通过电子邮件发送文件副本或创建自己的电子邮件功能(例如:how to send an email with attachement using powershell v1?)