This commit is contained in:
Edward Miller
2024-05-21 16:22:04 -05:00
committed by GitHub

View File

@@ -3,21 +3,23 @@ function ConvertTo-ExcelXlsx {
param param
( (
[parameter(Mandatory = $true, ValueFromPipeline)] [parameter(Mandatory = $true, ValueFromPipeline)]
[string]$Path, [string[]]$Path,
[parameter(Mandatory = $false)] [parameter(Mandatory = $false)]
[switch]$Force [switch]$Force
) )
process { process {
if (-Not ($Path | Test-Path) ) { try {
foreach ($singlePath in $Path) {
if (-Not ($singlePath | Test-Path) ) {
throw "File not found" throw "File not found"
} }
if (-Not ($Path | Test-Path -PathType Leaf) ) { if (-Not ($singlePath | Test-Path -PathType Leaf) ) {
throw "Folder paths are not allowed" throw "Folder paths are not allowed"
} }
$xlFixedFormat = 51 #Constant for XLSX Workbook $xlFixedFormat = 51 #Constant for XLSX Workbook
$xlsFile = Get-Item -Path $Path $xlsFile = Get-Item -Path $singlePath
$xlsxPath = "{0}x" -f $xlsFile.FullName $xlsxPath = [System.IO.Path]::ChangeExtension($xlsFile.FullName, ".xlsx")
if ($xlsFile.Extension -ne ".xls") { if ($xlsFile.Extension -ne ".xls") {
throw "Expected .xls extension" throw "Expected .xls extension"
@@ -38,25 +40,39 @@ function ConvertTo-ExcelXlsx {
} }
} }
if ($null -eq $Excel)
{
try { try {
$Excel = New-Object -ComObject "Excel.Application" $Excel = New-Object -ComObject "Excel.Application"
} }
catch { catch {
throw "Could not create Excel.Application ComObject. Please verify that Excel is installed." throw "Could not create Excel.Application ComObject. Please verify that Excel is installed."
} }
}
try { try {
$Excel.Visible = $false $Excel.Visible = $false
$null = $Excel.Workbooks.Open($xlsFile.FullName, $null, $true) $workbook = $Excel.Workbooks.Open($xlsFile.FullName, $null, $true)
$Excel.ActiveWorkbook.SaveAs($xlsxPath, $xlFixedFormat) if ($null -eq $workbook) {
Write-Host "Failed to open workbook"
} else {
$workbook.SaveAs($xlsxPath, $xlFixedFormat)
}
}
catch {
Write-Error ("Failed to convert {0} to XLSX." -f $xlsFile.FullName)
throw
} }
finally { finally {
if ($null -ne $Excel.ActiveWorkbook) { if ($null -ne $workbook) {
$Excel.ActiveWorkbook.Close() $workbook.Close()
} }
}
}
}
finally {
$Excel.Quit() $Excel.Quit()
$Excel = $null
} }
} }
} }