我試圖從報告服務下載文件。我第一次運行這個代碼時,它工作正常,但下次它不會覆蓋第一個下載的文件。我曾嘗試在創建WebClient對象之前添加刪除項目$文件,但是當我這樣做時,出現錯誤該進程無法訪問文件'D:\ Work \ RawMaterialCodes.xls',因爲它正在被另一個過程。,這個過程是Powershell本身。我曾嘗試致電$ webClient.Dispose()認爲這可能會釋放該文件,但沒有運氣。 有沒有人有任何想法如何覆蓋下載的文件和/或在下次嘗試之前將其刪除?Powershell WebClient.DownloadFile不覆蓋
$reportServer = "http://localhost/ReportServer_TRITON"
$reportName = "RawMaterialCodes"
$file = "D:\Work\RawMaterialCodes.xls"
$startDate = "2014-01-22"
$endDate = "2014-01-24"
$category = "Cat1"
$destination = ""
$reportUrl = $reportServer + "?/" + $reportName + "&StartDate=" + $startDate + "&EndDate=" + $endDate + "&Category=" + $category + "&Destination=" + $destination + "&rs:Format=Excel"
$webClient = new-object System.Net.WebClient
$webClient.Credentials = New-Object System.Net.NetworkCredential($userName, $password, $domain)
$webClient.DownloadFile($reportUrl, $file)
$mailMessage = new-object System.Net.Mail.MailMessage
$mailMessage.From = $emailFrom
$mailMessage.To.Add($emailTo)
$mailMessage.Subject = $emailSubject
$mailMessage.Body = $emailBody
$attachment = new-object System.Net.Mail.Attachment($file, 'text/plain')
$mailMessage.Attachments.Add($attachment)
$smtpClient = New-Object System.Net.Mail.SmtpClient($smtpServer, 25)
$smtpClient.EnableSsl = $enableSsl
if ($smtpAuthUsername -ne "")
{
$smtpClient.Credentials = New-Object System.Net.NetworkCredential($smtpAuthUsername, $smtpAuthPassword)
}
$smtpClient.Send($mailMessage)
我已經更新了這個問題,以顯示完整的腳本 – energ1ser
@ Energ1ser似乎最有可能被另一個進程持有。你關閉了所有可能引用這個文件的應用嗎? – JaredPar