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 = “test@dlabs.co.uk”
$msg.To.Add(”test@dlabs.co.uk”)
$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.
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()