Tuesday, 29 January 2013

File Locked After Sending SMTP Email with Powershell

In my previous blog post about sending emails with Powershell, I mentioned a problem where files that you attach to an email become locked until the instance of Powershell you are running has exited completely. So if you run a script through Powershell ISE that attaches a file to an email, that file will remain locked until you exit Powershell ISE.

If the file is locked by Powershell, you will get an error/warning message similar to the following if you try to modify it in any way;

The process cannot access the file 'c:\filename.txt' because it is being used by another process

By using the following command, you can ensure that Powershell 'disposes' of the email message once it has been sent and does not continue to 'lock' any files you attach and send via email;

$mailmessage.dispose()

Note: this is assuming that $MailMessage = New-Object system.net.mail.mailmessage 

1 comment:

  1. Need To Boost Your ClickBank Traffic And Commissions?

    Bannerizer makes it easy for you to promote ClickBank products by banners, simply visit Bannerizer, and grab the banner codes for your chosen ClickBank products or use the Universal ClickBank Banner Rotator to promote all of the ClickBank products.

    ReplyDelete