From 0f032c302192b2b9be34ac2e6c5512774c6e212b Mon Sep 17 00:00:00 2001 From: Andreas Jordan Date: Sat, 12 Sep 2026 15:25:41 +0200 Subject: [PATCH] Get-DbaWaitResource - Stop eating the caller loop on connection failure Stop-Function -Continue runs PowerShell's continue. No loop encloses this call site inside the command, so the continue unwound out of the command and consumed an iteration of whatever loop the caller runs in: a user's foreach silently skipped an element, and Pester's runner corrupted. The escape only bites the non-EnableException path; with EnableException Stop-Function throws before it gets there. Part of #10638 (do Get-DbaWaitResource) Co-Authored-By: Claude Fable 5.1 --- public/Get-DbaWaitResource.ps1 | 5 ++++- tests/Get-DbaWaitResource.Tests.ps1 | 27 ++++++++++++++++++++++++++- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/public/Get-DbaWaitResource.ps1 b/public/Get-DbaWaitResource.ps1 index 73a874388191..0d4c6f4d020c 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 f6ca1fd52041..fc95e7f90cba 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*" + } + } +}