@@ -55,11 +55,11 @@ function LogScriptInfo {
5555 $script :RunNumber = [int ]$Matches [1 ]
5656 }
5757 }
58- } else {
59- if ($null -ne $pkg ) { $pkg.Dispose () }
6058 }
6159 } catch {
6260 Write-Verbose " Unable to read existing run count from Excel: $_ "
61+ } finally {
62+ if ($null -ne $pkg ) { $pkg.Dispose () }
6363 }
6464 }
6565 $script :RunNumber ++
@@ -172,13 +172,33 @@ function LogScriptInfo {
172172 # Update snapshot so next identity only captures new errors
173173 $script :PreRunErrorCount = $Error.Count
174174
175- # Append to the existing Script Info tab
175+ # Append to the existing Script Info tab (skip -Append on first write when the tab doesn't exist yet)
176176 $savedEAP = $ErrorActionPreference
177177 $ErrorActionPreference = ' SilentlyContinue'
178- $infoExcel = $RunInfo | Export-Excel - Path $FileName - WorksheetName " Script Info" - Append - PassThru 3> $null
178+ $appendToSheet = $false
179+ if (Test-Path $FileName ) {
180+ try {
181+ $testPkg = Open-ExcelPackage - Path $FileName - ErrorAction SilentlyContinue
182+ if ($null -ne $testPkg -and $null -ne $testPkg.Workbook.Worksheets [" Script Info" ]) {
183+ $appendToSheet = $true
184+ }
185+ if ($null -ne $testPkg ) { $testPkg.Dispose () }
186+ } catch {
187+ Write-Verbose " Unable to check for existing Script Info tab: $_ "
188+ }
189+ }
190+
191+ if ($appendToSheet ) {
192+ $infoExcel = $RunInfo | Export-Excel - Path $FileName - WorksheetName " Script Info" - Append - PassThru 3> $null
193+ } else {
194+ $infoExcel = $RunInfo | Export-Excel - Path $FileName - WorksheetName " Script Info" - PassThru 3> $null
195+ }
179196 $ErrorActionPreference = $savedEAP
180- $infoExcel.Workbook.Worksheets [" Script Info" ].TabColor = [System.Drawing.Color ]::Gray
181- Export-Excel - ExcelPackage $infoExcel - WorksheetName " Script Info"
197+
198+ if ($null -ne $infoExcel ) {
199+ $infoExcel.Workbook.Worksheets [" Script Info" ].TabColor = [System.Drawing.Color ]::Gray
200+ Export-Excel - ExcelPackage $infoExcel - WorksheetName " Script Info"
201+ }
182202}
183203
184204function Export-TimelineExcel {
@@ -440,6 +460,12 @@ function SetLogRowTypeFilter {
440460 $tableStartCol = $tbl.Address.Start.Column
441461 $filterColId = $logRowCol - $tableStartCol
442462
463+ # Remove any existing filterColumn for this colId to avoid duplicates on reruns
464+ $existingFilterCol = $autoFilter.SelectSingleNode (" t:filterColumn[@colId='$filterColId ']" , $nsm )
465+ if ($null -ne $existingFilterCol ) {
466+ $null = $autoFilter.RemoveChild ($existingFilterCol )
467+ }
468+
443469 $filterCol = $tbl.TableXml.CreateElement (" filterColumn" , $ns )
444470 $filterCol.SetAttribute (" colId" , $filterColId.ToString ())
445471 $filters = $tbl.TableXml.CreateElement (" filters" , $ns )
0 commit comments