diff --git a/SharePointFunctions.ps1 b/SharePointFunctions.ps1 index 10c1360..af99555 100644 --- a/SharePointFunctions.ps1 +++ b/SharePointFunctions.ps1 @@ -484,17 +484,40 @@ function Convert-Files { $excel.DisplayAlerts = $false # Suppress Excel alerts try { - $workbook = $excel.Workbooks.Open($downloadPath) + # Convert paths to proper format for Excel + $excelDownloadPath = $downloadPath -replace "\\", "\\" + $excelXlsxPath = $xlsxPath -replace "\\", "\\" + + $workbook = $excel.Workbooks.Open($excelDownloadPath) + + # Save as XLSX using Excel constants + $xlOpenXMLWorkbook = 51 # Excel constant for XLSX format + $xlNormal = 1 # Excel constant for normal save + + # Use the Excel Application SaveAs2 method + $workbook.SaveAs2( + $excelXlsxPath, + $xlOpenXMLWorkbook, # FileFormat = xlsx + $null, # Password + $null, # WriteResPassword + $false, # ReadOnlyRecommended + $null, # CreateBackup + $xlNormal, # AccessMode + $null, # ConflictResolution + $true, # AddToMru + $null, # TextCodepage + $null, # TextVisualLayout + $false # Local + ) - # Save as XLSX using the full path - $workbook.SaveAs([string]$xlsxPath, 51) # 51 = xlOpenXMLWorkbook (*.xlsx) $workbook.Close($true) # True to save changes - Start-Sleep -Seconds 1 # Give Excel time to finish saving + Start-Sleep -Seconds 2 # Give Excel more time to finish saving - # Verify the file was created - if (-not (Test-Path -LiteralPath $xlsxPath)) { - throw "Excel SaveAs succeeded but file not found at: $xlsxPath" + # Verify the file was created using robust path checking + $verifyPath = [System.IO.Path]::GetFullPath($xlsxPath) + if (-not (Test-Path -LiteralPath $verifyPath)) { + throw "Excel SaveAs succeeded but file not found at: $verifyPath" } } finally { @@ -506,6 +529,9 @@ function Convert-Files { [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers() + + # Force Excel process cleanup + Get-Process -Name "EXCEL" -ErrorAction SilentlyContinue | Where-Object { $_.SI -eq [System.Security.Principal.WindowsIdentity]::GetCurrent().SessionId } | Stop-Process -Force } $script:txtStatus.Text += "Successfully converted to: $xlsxFileName`n"