Skip to content

Commit 9d458fd

Browse files
Set-DbaAgentOperator - Stop eating the caller loop on connection failure (#10653)
1 parent 7733198 commit 9d458fd

2 files changed

Lines changed: 35 additions & 1 deletion

File tree

‎public/Set-DbaAgentOperator.ps1‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,10 @@ function Set-DbaAgentOperator {
296296
try {
297297
$InputObject += Get-DbaAgentOperator -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Operator $Operator -EnableException
298298
} catch {
299-
Stop-Function -Message "Failed" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
299+
# No -Continue here: this catch sits before the operator loop, so the continue would
300+
# escape the command and eat an iteration of whatever loop the caller runs in.
301+
Stop-Function -Message "Failed" -Category ConnectionError -ErrorRecord $_ -Target $instance
302+
return
300303
}
301304
}
302305

‎tests/Set-DbaAgentOperator.Tests.ps1‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,4 +61,35 @@ Describe $CommandName -Tag IntegrationTests {
6161
$results.EmailAddress | Should -Be "new@new.com"
6262
}
6363
}
64+
65+
Context "When the instance cannot be reached" {
66+
BeforeAll {
67+
# Lower the connection timeout so the three failing connection attempts stay fast.
68+
$oldConnectionTimeout = Get-DbatoolsConfigValue -FullName sql.connection.timeout
69+
$null = Set-DbatoolsConfig -FullName sql.connection.timeout -Value 2
70+
}
71+
72+
AfterAll {
73+
$null = Set-DbatoolsConfig -FullName sql.connection.timeout -Value $oldConnectionTimeout
74+
}
75+
76+
It "Warns without eating an iteration of the caller's loop" {
77+
# The connection catch used to run Stop-Function -Continue before the operator loop -
78+
# the continue escaped the command and consumed an iteration of this very loop, so the
79+
# counter fell short (#10638).
80+
$loopCount = 0
81+
foreach ($i in 1..3) {
82+
$splatUnreachable = @{
83+
SqlInstance = "dbatoolsci-nohost"
84+
Operator = "dbatoolsci_nope"
85+
EmailAddress = "nope@nope.com"
86+
WarningAction = "SilentlyContinue"
87+
}
88+
$null = Set-DbaAgentOperator @splatUnreachable
89+
$loopCount++
90+
}
91+
$loopCount | Should -Be 3
92+
($WarnVar -join " ") | Should -BeLike "*Failed*"
93+
}
94+
}
6495
}

0 commit comments

Comments
 (0)