Question

I'm using the Send-MailMessage cmdlet to send a copy of a log file. However, I'd like to add a line to the log file with the status of the Send.

Code:

$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 {}

Error:

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

This works fine if the email succeeds, but if it fails (say the smtp server is unavailable), and erroraction is set to "Stop", then the file lock on the log file doesn't get released. If erroraction is not set to "Stop", then the log file gets released, but the Catch block doesn't get triggered.

I found a reference to the "dispose" method if you're rolling your own mail function, but I'm not sure how it could be used with the Send-MailMessage cmdlet: http://petermorrissey.blogspot.com.au/2013/01/sending-email-messages-with-powershell.html

Is there a command I should run to release the lock, or is this a bug, or am I going about this the wrong way?

Was it helpful?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top