I like exporting and sending the results of my Powershell scripts via SMTP mail.  That obviously require some sort of temporary location to hold my data while I am working on things.  However, I also try to stay away from dumping the temporary contents into TEMP or TMP.  I want to keep my junk separate from everyone, know exactly what should be in my temporary environment at a given time and clean everything up when I am done.

To achieve that, I always have a temporary location in my code where I keep my junk.  When I started to use that in conjunction with my mail-enabled scripts, I found that my temporary location was not being cleaned up consistently.  It was a bit hit-and-miss!  For example: Suppose you have a script that has a temporary file location in it but also has mail sending code similar to this:

$SMTPClient = new-object system.net.mail.smtpclient
$MailMessage = new-object system.net.mail.mailmessage
$SMTPClient.Host = $SMTPHost
$MailMessage.From = $Sender
$MailMessage.Subject = "Some Random Subject" 
$MailMessage.Body = "Some Random Body"

You may find that if you try to cleanup your temporary files and folder after sending the mail, it might not work consistently.  It’s also possible that upon debugging, you come across an error: “The process cannot access the file ‘somefile.csv’ because it is being used by another process” or something similar.

This is because good .NET programming (which Powershell is based on) requires releasing the resources and file handles after using a class, in this case, after sending the mail.  So, to avoid the problem, simply add the method:


after sending the mail and before the cleanup code.  This will release the resources that are held up in memory and the cleanup should be successful.

Hope this helps!