繁体   English   中英

Powershell - “该进程无法访问该文件,因为它正被另一个进程使用”

[英]Powershell - "The process cannot access the file because it is being used by another process"

我的脚本有问题,它从 SharePoint 2013 (OnPrem) 创建报告。 脚本将扫描数据并将其写入 csv 文件,并通过 SMTP 发送电子邮件,但在发送带有特定附件(报告)的电子邮件后,我从 Powershell 收到错误 - “该进程无法访问该文件,因为它正被另一个进程使用”

可能脚本仍在使用该文件,因为如果我停止脚本,我可以手动删除该文件。

    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

感谢 Theo 的回答( 在评论中):

在尝试删除文件之前,您需要在使用后销毁对象:$message.Dispose(); $smtp.Dispose()。 另外,您不应该在代码中使用卷曲的所谓“智能引号”,因为它会产生奇怪的错误。 使用直引号 " 和 '

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM