diff --git a/public/Add-DbaAgDatabase.ps1 b/public/Add-DbaAgDatabase.ps1 index 85eaf5ed1b..558c8f2e50 100644 --- a/public/Add-DbaAgDatabase.ps1 +++ b/public/Add-DbaAgDatabase.ps1 @@ -380,6 +380,14 @@ function Add-DbaAgDatabase { try { $replicaAgDb = Get-DbaAgDatabase -SqlInstance $replicaServerSMO[$replicaName] -AvailabilityGroup $AvailabilityGroup -Database $db.Name -EnableException + if ($null -eq $replicaAgDb) { + # We know the database has to exist by now, so we refresh the AvailabilityGroup object to update the cache that claims it doesn't. + $replicaAgDb = Get-DbaAgDatabase -Refresh -SqlInstance $replicaServerSMO[$replicaName] -AvailabilityGroup $AvailabilityGroup -Database $db.Name -EnableException + if ($null -eq $replicaAgDb) { + # throws to a catch + throw [System.Management.Automation.ItemNotFoundException]::New() + } + } } catch { $failure = $true Stop-Function -Message "Failed to get database $($db.Name) on replica $replicaName." -ErrorRecord $_ -Continue diff --git a/public/Get-DbaAgDatabase.ps1 b/public/Get-DbaAgDatabase.ps1 index 9e4d59e7cb..5214a27169 100644 --- a/public/Get-DbaAgDatabase.ps1 +++ b/public/Get-DbaAgDatabase.ps1 @@ -80,6 +80,14 @@ function Get-DbaAgDatabase { $InputObject += Get-DbaAvailabilityGroup -SqlInstance $SqlInstance -SqlCredential $SqlCredential -AvailabilityGroup $AvailabilityGroup } + foreach ($ag in $InputObject) { + $null = $ag.Refresh() + # Calling AvilabilityReplica.Refresh() has the side effct of updating AvailabilityDatabases. + # calling AvailabilityDatabases.Refresh() alone is not enough + $null = $ag.AvailabilityReplicas.Refresh() + $null = $ag.AvailabilityDatabases.Refresh() + } + foreach ($db in $InputObject.AvailabilityDatabases) { if ($Database) { if ($db.Name -notin $Database) { continue }