I have problem with my script which create report from SharePoint 2013 (OnPrem). Script will scan and write data to csv file and send e-mail via SMTP but after sending e-mail with specific attachment (report) I get error from Powershell - "The process cannot access the file because it is being used by another process"
Probably script still using this file, because if I stop the script, manually I can delete the file.
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
# Pause for 0.1 second per loop
Do {
# Do stuff
# Sleep 100 Milliseconds
Start-Sleep -Milliseconds 100
}
while ($condition -eq $true)
#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”
$attachment = "c:\ListData.txt"
$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$smtp.Send($message)
# Pause for 10 seconds per loop
Do {
# Do stuff
# Sleep 10000 Milliseconds
Start-Sleep -Milliseconds 10000
}
while ($condition -eq $true)
rm -fo c:\ListData.txt
write-host "Export odoslaný na určených príjemcov" -ForegroundColor Green
Thanks to Theo for his answer (in the comments):
You need to destroy the objects after use before you try and delete the file: $message.Dispose(); $smtp.Dispose(). As aside, you should not use curly so-called 'smartquotes' in code as that can provide weird errors. Use straight quotes " and '