.NET Framework - locked files

Asked By ada on 31-Mar-09 12:29 PM
I have ps1 script sending email with attachments. After run that script i
need to delete sent files, but I can't - it says me that files are used by
another proccess (means powershell console). How to unlock access to that
files from PowerShell without closing PS console?

Keith Hill [MVP] replied on 31-Mar-09 11:25 PM
How are you sending the message?  If you are scripting it all, make sure you
are disposing the appropriate objects (FileStream and MailAttachment both
require disposing to close the file).  If you are using a cmdlet and don’t
have the ability to dispose, then try execute [GC]::Collect() to force
cleanup of resources and closing of the file.

ada replied on 01-Apr-09 12:46 PM
I simpy do this:

$filename = “logfile.txt”
$smtpServer = “localhost”
$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($filename)
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = “somebody@yourdomain.com”
$msg.Subject = “Nightly Log File”
$msg.Body = “The nightly log file is attached”

and after that file logfile.txt is locked and I cannot delete it until
closing PS console. What should I do?
Marco Shaw [MVP] replied on 01-Apr-09 02:32 PM
As Keith indicates, at the end of the above code, simply add:

Give that a try.  I think this has come up a few times in this group
recently enough.

Try going here and searching for "Attachment":


*Microsoft MVP - Windows PowerShell
*Co-Author - Sams Windows PowerShell Unleashed 2nd Edition
*PowerShell Co-Community Director - http://www.powershellcommunity.org
*Blog - http://marcoshaw.blogspot.com