我被困在一個腳本的末尾,我正在處理一個文件被刪除之前通過電子郵件發送出去的地方。除了...該文件似乎仍然可以通過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}
線條註釋是我在注射暫停和垃圾清除嘗試,取得了相同的結果。
真棒!謝謝! – 2010-11-30 23:17:25