[英]Decreasing performance for excel com object in powershell script
我用過一個Powershell腳本,該腳本創建一個excel com對象以重復讀取* .csv文件,生成圖形,然后將圖形另存為* .pdf文件。 代碼段如下所示。 腳本啟動時,每個文件需要2-4秒。 腳本運行時間越長,處理單個csv文件所需的時間就越長。 大約1,000個文件后,每個文件大約需要60秒。 所有的csv文件都是2列乘70行。 當我有215張圖要生成時,運行大約需要12分鍾。 當我有1,522張圖時,需要20多個小時。 我可以做些什么來加快速度嗎?
Tia,馬克·K。
#
# Create an Excell object and use it to generate the graphs.
#
$ex = New-Object -ComObject Excel.Application
$chartType = "microsoft.office.interop.excel.xlChartType" -as [type]
$xlFixedFormat = "Microsoft.Office.Interop.Excel.xlFixedFormatType" -as [type]
$ex.DisplayAlerts = $False
$ex.Visible = $False
$wb = $ex.Workbooks.Add()
$ws = $wb.worksheets
$ws1 = $ws.Item(1)
try { # Delete unneeded worksheets, if present
$ws.item(3).delete()
$ws.item(2).delete()
}
catch [Exception] {
Out-Null
}
$i = 0
foreach ($p in $pdfs) { # $p is a csv file to be the source for a pdf
Try {
$ws1.Name = $p.Substring(0,$p.IndexOf('.'))
$Connector = ("text;http://xxxxxxxxxxxxx/" + $lpar + "/" + $p)
$CellRef = $ws1.Range("A1")
$Conn = $ws1.QueryTables.Add($Connector,$CellRef)
$ws1.QueryTables.item($Conn.name).TextFileCommaDelimiter = $True
$ws1.QueryTables.item($Conn.name).TextFileParseType = 1
$ws1.QueryTables.item($Conn.name).Refresh() | Out-Null
$ws2 = $ex.charts.add()
$ws2.chartType = $chartType::xlLine
$ws2.Name = $ws1.Name + " Graph"
$ws2.HasTitle = $True
$ws2.ChartTitle.Text = $ws1.Range("A1").text
$Data = $ws1.range("b2:b71")
$ws2.setSourceData($Data) | Out-Null
$ws2.SeriesCollection(1).XValues = $ws1.Range("A2:A71")
$wb.ExportAsFixedFormat($xlFixedFormat::xlTypePDF,"$drive`:\captrendGraphs\$lpar\" + $ws1.Name + ".pdf",0,$True,$True,1,1)
$ws2.Delete() | Out-Null
$ws1.UsedRange.ClearContents() | Out-Null
}
catch [Exception] {
Write-Host $_.Exception.toString()
Write-Log $($_.Exception.toString())
Write-Host $_.Exception.message
Write-Log $($_.Exception.message)
Write-Host $_.Exception.source
Write-Log $($_.Exception.source)
Write-Host $_.Exception.StackTrace
Write-Log $($_.Exception.StackTrace)
Write-Host "Error occured with: " $p
Write-Log $("Error occured with: " + $p)
}
$i++
$rptP = $("{0:D4}" -f $i + " " + $p)
Write-Host $rptP
Write-Log $rptP
}
您可以按時間間隔(15分鍾)或圖形創建間隔(每1000個)打開和關閉一個新的excel會話,看看是否有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.