PowerShell Close File/Delete File After Emailing via .NET -


i'm stuck @ end of script working on file emailed out before being deleted. except.. file seems still opened, smtp client, error when try delete it. of course restarting shell let me delete it, thats not point. ;-) point i'd create it, email it, delete it, in 1 script.

the error:

   cannot remove item c:\temp\myfile.csv: process cannot access file     'c:\temp\myfile.csv' because being used process. 

code:

$emailfrom = 'noreply@localhost' $emailto = 'aaron@localhost' $smtpserver = 'localhost'  $filename='myfile.csv' $filepathname='c:temp\' + $filename  $subject = 'emailing: ' + $filename $body = 'this message been sent 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 releasing file 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 attempts @ injecting pauses , garbage cleanup, yielded same result.

dispose attachment , email objects

$att.dispose(); $msg.dispose(); 

doing gc won't help, still have root refs


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -