Skip to content

Commit

Permalink
optionally cache to temp file to avoid locking issues
Browse files Browse the repository at this point in the history
  • Loading branch information
edwardmiller-mesirow committed May 22, 2024
1 parent b6034c3 commit 4d297bd
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions Public/ConvertTo-ExcelXlsx.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ function ConvertTo-ExcelXlsx {
[parameter(Mandatory = $true, ValueFromPipeline)]
[string[]]$Path,
[parameter(Mandatory = $false)]
[switch]$Force
[switch]$Force,
[parameter(Mandatory = $false)]
[switch]$CacheToTemp
)
process {
try {
Expand All @@ -19,7 +21,6 @@ function ConvertTo-ExcelXlsx {

$xlFixedFormat = 51 #Constant for XLSX Workbook
$xlsFile = Get-Item -Path $singlePath
$xlsxPath = [System.IO.Path]::ChangeExtension($xlsFile.FullName, ".xlsx")

if ($xlsFile.Extension -ne ".xls") {
throw "Expected .xls extension"
Expand Down Expand Up @@ -50,13 +51,30 @@ function ConvertTo-ExcelXlsx {
}
}

if ($CacheToTemp) {
$tempPath = [System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), [System.IO.Path]::GetFileName($xlsFile.FullName))
Copy-Item -Path $xlsFile.FullName -Destination $tempPath -Force
$fileToProcess = $tempPath
}
else {
$fileToProcess = $xlsFile.FullName
}

$xlsxPath = [System.IO.Path]::ChangeExtension($fileToProcess, ".xlsx")

try {
$Excel.Visible = $false
$workbook = $Excel.Workbooks.Open($xlsFile.FullName, $null, $true)
$workbook = $Excel.Workbooks.Open($fileToProcess, $null, $true)
if ($null -eq $workbook) {
Write-Host "Failed to open workbook"
} else {
$workbook.SaveAs($xlsxPath, $xlFixedFormat)

if ($CacheToTemp) {
$originalXlsxPath = [System.IO.Path]::ChangeExtension($xlsFile.FullName, ".xlsx")
Copy-Item -Path $xlsxPath -Destination $originalXlsxPath -Force
Remove-Item -Path $xlsxPath -Force
}
}
}
catch {
Expand All @@ -69,6 +87,10 @@ function ConvertTo-ExcelXlsx {
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($workbook) | Out-Null
$workbook = $null
}

if ($CacheToTemp) {
Remove-Item -Path $tempPath -Force
}
}
}
}
Expand Down

0 comments on commit 4d297bd

Please sign in to comment.