PowerShell脚本发送SharePoint报表后删除文件提示被占用问题
解决PowerShell发送邮件后无法删除附件文件的问题
问题原因
你遇到的文件占用错误,是因为System.Net.Mail.Attachment和MailMessage对象在发送邮件后没有释放文件句柄。即使SmtpClient.Send()执行完成,这些对象仍会保留对文件的锁定,导致后续删除操作失败。另外你脚本里的两个Do-While循环因为$condition未定义,根本不会执行,可以直接移除。
解决方案
发送邮件后,必须手动调用Attachment.Dispose()和MailMessage.Dispose()释放资源,或者使用PowerShell的using语句自动管理对象生命周期(推荐)。
修改后的完整脚本
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue cls; #Get the Web $web = Get-SPWeb -identity "SharePoint URL" #Get the Target List $list = $web.Lists["SharePoint List"] #Array to Hold Result - PSObjects $ListItemCollection = @() $date = (get-date).ToString("dd.MM.yyyy") #Get All List items where Status is "In Progress" $list.Items | Where-Object { $_["Stav_Požiadavka"] -match "Požadované"} | foreach { $ExportItem = New-Object PSObject $a = $_["Editor"] -replace ';','' -replace '#','' -replace '\d+','' $ExportItem | Add-Member -MemberType NoteProperty -name "Spracovatel" -value $_["Meno_Priezvisko_Spracovateľ"] $ExportItem | Add-Member -MemberType NoteProperty -Name "Vytvorene" -value $_["Created"] $ExportItem | Add-Member -MemberType NoteProperty -name "RodneCislo" -value $_["Rodn_x00e9___x010c__x00ed_slo_Klient"] $ExportItem | Add-Member -MemberType NoteProperty -name "Upravene" -value $_["Modified"] $ExportItem | Add-Member -MemberType NoteProperty -name "Upravil" -value $a #Add the object with property to an Array $ListItemCollection += $ExportItem } #Export the result Array to CSV file $ListItemCollection | Export-CSV "c:\ListData.txt" -NoTypeInformation -Encoding utf8 #Dispose the web Object $web.Dispose() write-host "Export úspešné dokončený" -ForegroundColor Green #Send export via SMTP $fromaddress = "sender e-mail address" $toaddress = "receiver e-mail address" $Subject = "Export otvorených žiadostí v aplikácii UmrtieKlienta k "+$date $body = "test" $smtpserver = "SMTP server" $attachmentPath = "c:\ListData.txt" # 使用using语句自动管理资源,发送完成后自动释放文件句柄 using ($message = New-Object System.Net.Mail.MailMessage) { $message.From = $fromaddress $message.To.Add($toaddress) $message.IsBodyHtml = $True $message.Subject = $Subject $message.Body = $body using ($attach = New-Object Net.Mail.Attachment($attachmentPath)) { $message.Attachments.Add($attach) using ($smtp = New-Object Net.Mail.SmtpClient($smtpserver)) { $smtp.Send($message) } } } # 现在可以正常删除文件了 rm -fo $attachmentPath write-host "Export odoslaný na určených príjemcov" -ForegroundColor Green
关键修改点
- 移除了无意义的
Do-While循环 - 使用
using语句包裹MailMessage、Attachment和SmtpClient对象,确保对象使用完毕后自动调用Dispose()释放资源,包括文件句柄 - 把附件路径存为变量
$attachmentPath,避免重复写路径
如果你的PowerShell版本低于5.1(不支持using语句),可以手动调用Dispose()替代:
# 发送邮件后手动释放资源 $attach.Dispose() $message.Dispose() $smtp.Dispose()
内容的提问来源于stack exchange,提问作者jck4real
相关产品推荐
相关产品推荐

