Wait for an AlwaysOn replica to be synchronized in Powershell I am working on a disaster recovery script. One part of it is not being consistent. 

This is the code:

...
## Switch replica to Synchronous
Set-SqlAvailabilityReplica -AvailabilityMode "SynchronousCommit" `
-Path SQLSERVER:\Sql\Server1\Instance\AvailabilityGroups\SCOM-DBs\AvailabilityReplicas\Server2

## Wait until the replica is synchronized
$NewPrimary = Get-Item SQLSERVER:\Sql\Server1\Instance\AvailabilityGroups\AG-DBs\AvailabilityReplicas\Server2

Write-Host -NoNewline "Waiting for DBs to be synchronized"
while ($NewPrimary.RollupSynchronizationState -notlike 'Synchronized') {
   Write-Host  -NoNewline "."
   Start-Sleep -s 2
}
...


Sometimes gets synchronizing and it does not change even though SSMS dashboard changes. Is there a better in Powershell way to detect when the replica is synchronized?
I found my problem.

I was working under the wrong assumption that the objects were automatically refreshed in Powershell. I added a "$NewPrimary.Refresh()" insinde of the while loop and that did the trick.

I hope this helps someone with the same wrong assumption in the future.