I'm stuck at the end of a script I am working on where a file is emailed out before being deleted. Except.. the file seems to be still be opened, likely by the SMTP client, so I get an error when I try to delete it. Of course restarting a shell will let me delete it, thats not the point. ;-) Point is I'd like to create it, email it, delete it, in one script.
The Error:
Cannot remove item C:\Temp\myfile.csv: The process cannot access the file
'C:\Temp\myfile.csv' because it is being used by another process.
Code:
$emailFrom = 'noreply@localhost'
$emailTo = 'aaron@localhost'
$smtpServer = 'localhost'
$FileName='myfile.csv'
$FilePathName='c:temp\' + $FileName
$subject = 'Emailing: ' + $FileName
$body = 'This message as been sent with the following file or link attachments: ' + $FileName
$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($FilePathName)
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = $emailFrom
$msg.To.Add($emailTo)
$msg.Subject = $subject
$msg.Body = $body
$msg.Attachments.Add($att)
$smtp.Send($msg)
#Garbage Collection (used for releasing file for deleting)
# Start-Sleep -s 1
# [GC]::Collect()
#Clean-up/Remove File
# Start-Sleep -s 1
if (Test-Path $FilePathName) {Remove-Item $FilePathName}
The lines commented out are my attempts at injecting pauses and garbage cleanup, which yielded the same result.
Dispose the attachment and email objects
$att.Dispose();
$msg.Dispose();
doing a GC won't help, as you still have root refs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With