Two errors thrown when a worksheet cannot be found
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

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.
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
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.
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.