PowerShell通过.NET发送电子邮件后关闭文件/删除文件

时间:2010-11-30 23:02:40

标签: .net powershell

我被困在我正在处理的脚本的末尾,在删除之前将文件通过电子邮件发送出去。除了..文件似乎仍然可能被SMTP客户端打开,所以当我尝试删除它时出现错误。当然重启shell会让我删除它,这不是重点。 ;-)点我想在一个脚本中创建它,通过电子邮件发送,删除它。

错误:

   Cannot remove item C:\Temp\myfile.csv: The process cannot access the file
    'C:\Temp\myfile.csv' because it is being used by another process.

代码:

$emailFrom = 'noreply@localhost'
$emailTo = 'aaron@localhost'
$smtpServer = 'localhost'

$FileName='myfile.csv'
$FilePathName='c:temp\' + $FileName

$subject = 'Emailing: ' + $FileName
$body = 'This message as been sent with the following file or link attachments: ' + $FileName

$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($FilePathName)
$smtp = new-object Net.Mail.SmtpClient($smtpServer)

$msg.From = $emailFrom
$msg.To.Add($emailTo)
$msg.Subject = $subject
$msg.Body = $body
$msg.Attachments.Add($att)
$smtp.Send($msg)

#Garbage Collection (used for releasing file for deleting)
# Start-Sleep -s 1
# [GC]::Collect()

#Clean-up/Remove File
# Start-Sleep -s 1
if (Test-Path $FilePathName) {Remove-Item $FilePathName}

注释掉的线条是我尝试注入暂停和垃圾清理,这产生了相同的结果。

2 个答案:

答案 0 :(得分:11)

处理附件和电子邮件对象

$att.Dispose();
$msg.Dispose();

执行GC无济于事,因为你仍然有root refs

答案 1 :(得分:0)

Powershell v2发布了Send-MailMessage Cmdlet,它自动处理引用。

SYNTAX
    Send-MailMessage [-To] <string[]> [-Subject] <string> -From <string> 
    [[-Body] <string>] [[-SmtpServer] <string>] [-Attachments <string[]>]
    [-Bcc <string[]>] [-BodyAsHtml] [-Cc <string[]>] [-Credential <PSCredential>]
    [-DeliveryNotificationOption {None | OnSuccess | OnFailure | Delay | Never}]
    [-Encoding <Encoding>] [-Priority {Normal | Low | High}]
    [-UseSsl] <CommonParameters>]

在你的情况下,这将是:

$emailFrom = 'noreply@localhost'
$emailTo = 'aaron@localhost'
$smtpServer = 'localhost'

$FileName='myfile.csv'
$FilePathName= [System.Io.Path]::Combine('c:\temp\', $FileName)

$subject = 'Emailing: ' + $FileName
$body = 'This message as been sent with the following file or link attachments: ' + $FileName

Send-MailMessage -To $emailTo -From $emailFrom -Subject $subject -Body $body -Attachments $filePathName -SmtpServer $smtpserver -Encoding ([System.Text.Encoding]::UTF8)

#Clean-up/Remove File
if (Test-Path $FilePathName) {Remove-Item $FilePathName}

有关详细信息,请参阅technet