From 6336ca8c032541e4d01654e1e466fc06ae9b1993 Mon Sep 17 00:00:00 2001 From: Adam Lancaster <68036988+lancasteradam@users.noreply.github.com> Date: Thu, 11 Mar 2021 01:53:15 -0800 Subject: [PATCH] Import-DbaCsv - ensure the reader is closed in the inner loop (#7165) --- functions/Import-DbaCsv.ps1 | 47 +++++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 15 deletions(-) diff --git a/functions/Import-DbaCsv.ps1 b/functions/Import-DbaCsv.ps1 index c6ff443d4b..ac30d06d25 100644 --- a/functions/Import-DbaCsv.ps1 +++ b/functions/Import-DbaCsv.ps1 @@ -644,8 +644,6 @@ function Import-DbaCsv { Write-Progress -id 1 -activity "Inserting $resultcount rows" -status "Complete" -Completed } - $reader.Close() - $reader.Dispose() $completed = $true } catch { $completed = $false @@ -654,14 +652,43 @@ function Import-DbaCsv { Write-Progress -id 1 -activity "Inserting $resultcount rows" -status "Failed" -Completed } Stop-Function -Continue -Message "Failure" -ErrorRecord $_ + } finally { + try { + $reader.Close() + $reader.Dispose() + } catch { + } + + if (-not $NoTransaction) { + if ($completed) { + try { + $null = $transaction.Commit() + } catch { + } + } else { + try { + $null = $transaction.Rollback() + } catch { + } + } + } + + try { + $sqlconn.Close() + $sqlconn.Dispose() + } catch { + } + + try { + $bulkCopy.Close() + $bulkcopy.Dispose() + } catch { + } } } if ($PSCmdlet.ShouldProcess($instance, "Finalizing import")) { if ($completed) { # "Note: This count does not take into consideration the number of rows actually inserted when Ignore Duplicates is set to ON." - if (-not $NoTransaction) { - $null = $transaction.Commit() - } $rowscopied = Get-BulkRowsCopiedCount $bulkcopy $rps = [int]($rowscopied / $elapsed.Elapsed.TotalSeconds) @@ -684,16 +711,6 @@ function Import-DbaCsv { return } } - - # Close everything just in case & ignore errors - try { - $null = $sqlconn.close(); $null = $sqlconn.Dispose(); - $null = $bulkCopy.close(); $bulkcopy.dispose(); - $null = $reader.close(); $null = $reader.dispose() - } catch { - #here to avoid an empty catch - $null = 1 - } } } }