ImportExcel icon indicating copy to clipboard operation
ImportExcel copied to clipboard

Two errors thrown when a worksheet cannot be found

Open DarkLite1 opened this issue 3 years ago • 3 comments

When using `Import-Excel' to retrieve the content of a specific worksheet that is not available there are two errors thrown while only one is expected.

Example

$params = @{
    Path          = New-TemporaryFile | 
    Rename-Item -NewName { $_ -replace 'tmp$', 'xlsx' } -PassThru
    WorksheetName = 'Sheet1'
}
@(
    [PSCustomObject]@{'Fruit' = 'Banana' }
    [PSCustomObject]@{'Fruit' = 'Kiwi' }
) | Export-Excel @params

Import-Excel -Path $params.Path -WorksheetName 'nonExisting'

Errors

image

Expected

Only one error:

Failed importing the Excel workbook 'C:\Users\bgijbels\AppData\Local\Temp\3\tmp3039.xlsx' with worksheet 'nonExisting': Worksheet 'nonExisting' not found, the workbook only contains the worksheets 'Sheet1'. If you orkbook only contains the worksheets 'Sheet1'. If you only wish to select the first worksheet, please remove the '-WorksheetName' parameter.

DarkLite1 avatar Jun 01 '22 06:06 DarkLite1

Why not use a try/catch block?

$params = @{
    Path          = New-TemporaryFile | 
    Rename-Item -NewName { $_ -replace 'tmp$', 'xlsx' } -PassThru
    WorksheetName = 'Sheet1'
}
@(
    [PSCustomObject]@{'Fruit' = 'Banana' }
    [PSCustomObject]@{'Fruit' = 'Kiwi' }
) | Export-Excel @params

try{
    Import-Excel -Path $params.Path -WorksheetName 'nonExisting'
} catch {
    Write-Host "Oops not valid information"
}

Output is:

Oops not valid information

NoralK avatar Jun 22 '22 16:06 NoralK

That's what we already do. In normal circumstances a terminating error of a function only throws a single error and does not pollute the error object with multiple errors originating from the same function.

So in a sense, you're right, try/catch is the way. But it should be done in the function and clean-up the old produced errors into one really easily digestible error message for the end user. Hence, that's why I already made the PR to fix this.

DarkLite1 avatar Jun 23 '22 06:06 DarkLite1

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Jul 31 '22 08:07 stale[bot]