From dfb9dc35573b78a767062765e1b22974a1325d41 Mon Sep 17 00:00:00 2001 From: "Bobby Abellana (aider)" Date: Fri, 21 Feb 2025 10:58:34 -0800 Subject: [PATCH] fix: handle spaces in Excel SaveAs paths and add file verification --- SharePointFunctions.ps1 | 41 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/SharePointFunctions.ps1 b/SharePointFunctions.ps1 index fe34831..71ef43e 100644 --- a/SharePointFunctions.ps1 +++ b/SharePointFunctions.ps1 @@ -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"