diff --git a/public/Get-DbaWaitResource.ps1 b/public/Get-DbaWaitResource.ps1 index 73a87438819..0d4c6f4d020 100644 --- a/public/Get-DbaWaitResource.ps1 +++ b/public/Get-DbaWaitResource.ps1 @@ -111,7 +111,10 @@ function Get-DbaWaitResource { try { $server = Connect-DbaInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential } catch { - Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue + # No -Continue here: this block has no enclosing loop, so the continue would escape the command + # and eat an iteration of whatever loop the caller runs in (#10638). + Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance + return } $null = $WaitResource -match '^(?[A-Z]*): (?[0-9]*):*' diff --git a/tests/Get-DbaWaitResource.Tests.ps1 b/tests/Get-DbaWaitResource.Tests.ps1 index f6ca1fd5204..fc95e7f90cb 100644 --- a/tests/Get-DbaWaitResource.Tests.ps1 +++ b/tests/Get-DbaWaitResource.Tests.ps1 @@ -157,4 +157,29 @@ Describe $CommandName -Tag IntegrationTests { $resultskey.ObjectData.col2 | Should -Be "bilbo" } } -} \ No newline at end of file + + Context "When the instance cannot be reached" { + BeforeAll { + # Lower the connection timeout so the three failing connection attempts stay fast. + $oldConnectionTimeout = Get-DbatoolsConfigValue -FullName sql.connection.timeout + $null = Set-DbatoolsConfig -FullName sql.connection.timeout -Value 2 + } + + AfterAll { + $null = Set-DbatoolsConfig -FullName sql.connection.timeout -Value $oldConnectionTimeout + } + + It "Warns without eating an iteration of the caller's loop" { + # The connection catch used to run Stop-Function -Continue in the process block, where no loop + # encloses it - the continue escaped the command and consumed an iteration of this very loop, so + # the counter stayed at zero (#10638). + $loopCount = 0 + foreach ($i in 1..3) { + $null = Get-DbaWaitResource -SqlInstance dbatoolsci-nohost -WaitResource "PAGE: 1:1:1" -WarningAction SilentlyContinue + $loopCount++ + } + $loopCount | Should -Be 3 + ($WarnVar -join " ") | Should -BeLike "*Failure*" + } + } +}