diff --git a/public/New-DbaAzAccessToken.ps1 b/public/New-DbaAzAccessToken.ps1 index dcfba2de3fd..011066950c4 100644 --- a/public/New-DbaAzAccessToken.ps1 +++ b/public/New-DbaAzAccessToken.ps1 @@ -254,7 +254,9 @@ function New-DbaAzAccessToken { } } } catch { - Stop-Function -Message "Failure" -ErrorRecord $_ -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" -ErrorRecord $_ } } } \ No newline at end of file diff --git a/tests/New-DbaAzAccessToken.Tests.ps1 b/tests/New-DbaAzAccessToken.Tests.ps1 index fb4271a5be0..c17be29fb8c 100644 --- a/tests/New-DbaAzAccessToken.Tests.ps1 +++ b/tests/New-DbaAzAccessToken.Tests.ps1 @@ -28,4 +28,33 @@ Describe $CommandName -Tag UnitTests { Integration test should appear below and are custom to the command you are writing. Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests for more guidence. -#> \ No newline at end of file +#> +Describe $CommandName -Tag IntegrationTests { + Context "When the service principal cannot be authenticated" { + BeforeAll { + $badPassword = ConvertTo-SecureString -String "dbatoolsci" -AsPlainText -Force + $badCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "dbatoolsci", $badPassword + } + + # The ServicePrincipal path is the one that reaches the catch: it refuses to run on Core before any + # request is made, so the test runs on Windows PowerShell only, which is what CI runs anyway. + It "Warns without eating an iteration of the caller's loop" -Skip:($PSVersionTable.PSEdition -eq "Core") { + # The catch used to run Stop-Function -Continue at the end of 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). A tenant that does not exist makes the token request fail. + $loopCount = 0 + foreach ($i in 1..3) { + $splatBadTenant = @{ + Type = "ServicePrincipal" + Tenant = "dbatoolsci.invalid" + Credential = $badCredential + WarningAction = "SilentlyContinue" + } + $null = New-DbaAzAccessToken @splatBadTenant + $loopCount++ + } + $loopCount | Should -Be 3 + ($WarnVar -join " ") | Should -BeLike "*Failure*" + } + } +}