fix: handle spaces in Excel SaveAs paths and add file verification

This commit is contained in:
Bobby Abellana (aider) 2025-02-21 10:58:34 -08:00
parent c6c0769384
commit dfb9dc3557

View File

@ -469,7 +469,10 @@ function Convert-Files {
# Convert the file to XLSX
$xlsxFileName = $originalFileName -replace "\.xls[m]?$", ".xlsx"
$xlsxPath = "$env:TEMP\$xlsxFileName"
# Use Join-Path to properly handle paths with spaces
$xlsxPath = Join-Path $env:TEMP $xlsxFileName
$downloadPath = Join-Path $env:TEMP $originalFileName
try {
# Open Excel
$excel = New-Object -ComObject Excel.Application
@ -479,9 +482,14 @@ function Convert-Files {
try {
$workbook = $excel.Workbooks.Open($downloadPath)
# Save as XLSX
$workbook.SaveAs($xlsxPath, 51) # 51 = xlOpenXMLWorkbook (*.xlsx)
# Save as XLSX - use the full path with quotes
$workbook.SaveAs([string]$xlsxPath, 51) # 51 = xlOpenXMLWorkbook (*.xlsx)
$workbook.Close($false)
# Verify the file was created
if (-not (Test-Path $xlsxPath)) {
throw "Excel SaveAs succeeded but file not found at: $xlsxPath"
}
}
finally {
# Proper cleanup of Excel COM objects
@ -495,6 +503,33 @@ function Convert-Files {
}
$script:txtStatus.Text += "Successfully converted to: $xlsxFileName`n"
# Upload the converted file to SharePoint
try {
# Verify file exists before trying to read it
if (-not (Test-Path $xlsxPath)) {
throw "Converted file not found at: $xlsxPath"
}
# Get the destination folder
$destinationFolder = $script:txtTempLib.Text
$uploadUri = "https://graph.microsoft.com/v1.0/drives/$($drive.Id)/root:/$($destinationFolder)/$($xlsxFileName):/content"
# Read the file content
$fileContent = [System.IO.File]::ReadAllBytes($xlsxPath)
# Upload the file
Invoke-MgGraphRequest -Uri $uploadUri -Method PUT -Body $fileContent -ContentType "application/octet-stream"
$script:txtStatus.Text += "Successfully uploaded to SharePoint: $destinationFolder/$xlsxFileName`n"
}
catch {
$script:txtStatus.Text += "Error uploading file: $($_.Exception.Message)`n"
if (-not (Test-Path $xlsxPath)) {
$script:txtStatus.Text += "File not found at: $xlsxPath`n"
}
continue # Move to the next file
}
}
catch {
$script:txtStatus.Text += "Error converting file: $($_.Exception.Message)`n"