2010-11-30 98 views
4

我被困在一個腳本的末尾,我正在處理一個文件被刪除之前通過電子郵件發送出去的地方。除了...該文件似乎仍然可以通過SMTP客戶端打開,所以當我嘗試刪除它時出現錯誤。當然重新啓動一個shell會讓我刪除它,那不是重點。 ;-)問題是我想創建它,用電子郵件發送,刪除它,在一個腳本中。PowerShell通過.NET電子郵件關閉文件/刪除文件

的錯誤:

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 = '[email protected]' 
$emailTo = '[email protected]' 
$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} 

線條註釋是我在注射暫停和垃圾清除嘗試,取得了相同的結果。

回答

10

處置附件和電子郵件對象

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

做GC不會幫助,因爲你仍然有根裁判

+0

真棒!謝謝! – 2010-11-30 23:17:25

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 = '[email protected]' 
$emailTo = '[email protected]' 
$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

相關問題