簡體   English   中英

釋放send-mailmessage出錯的文件鎖

[英]Release a file lock that send-mailmessage leaves on error

我正在使用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服務器不可用),並且錯誤被設置為“停止”,則日志文件上的文件鎖定不會被釋放。 如果錯誤設置為“停止”,則日志文件將被釋放,但Catch塊不會被觸發。

如果您正在編輯自己的郵件功能,我找到了對“dispose”方法的引用,但我不確定它如何與Send-MailMessage cmdlet一起使用: http//petermorrissey.blogspot.com.au/ 2013/01 /發送電子郵件的消息與- 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方法創建自己的電子郵件功能(一個示例: 如何使用powershell v1發送帶附件的電子郵件?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM