tags:

views:

109

answers:

2

I am looking to create a script that emails and moves files recursively for all the files in a specified folder.

So for each file it will: Email File1 move File1 Email File2 Move File2 Etc.

Now when I run the script below I get the following message: The process cannot access the file because it is being used by another process.

$files = Get-ChildItem 'c:\Test\Out\'

ForEach ($file in $files) 
    {$smtpServer = “mail.dlabs.local”

    $msg = New-Object Net.Mail.MailMessage
    $att = New-Object Net.Mail.Attachment($file.FullName)
    $smtp = New-Object Net.Mail.SmtpClient($smtpServer)

    $msg.From = “[email protected]”
    $msg.To.Add(”[email protected]”)
    $msg.Subject =  ("Test Message "+ $file.Name)
    $msg.Body = “”
    $msg.Attachments.Add($att)

    $smtp.Send($msg)

    Move-Item $moveFile.FullName 'c:\Test\Sent'}

If anyone could help me with this it would be most appreciated.

+2  A: 

That's because a file handle is already opened for the file you're trying to move.

The Net.Mail.Attachment implements IDisposable, so to release the file lock you should call $att.Dispose()

Alexandru Nedelcu
A: 

Hi,

Call .Dispose() on the msg object.

If that doesn't work, you may also want to call .Disposse on the Attachment object first, and then .Dispose() on the msg object.

(I think you only have to call .Dispose() on the msg object, but I can't remember...been a while since I tested that code).

Cheers!

Dave

dave wanta