Last week I was working on a couple of SQL instances that contained databases which were part of an Always On availability group, with one server being the primary and the other the secondary.
I needed to make sure that the secondary had all the databases that were on the primary (darn you auto seeding!!). The problem was that these instances had over 200 databases which meant checking them was no simple task.
Now I know there’s a few ways to do this but the method I used is a simple & quick way of comparing databases on two SQL instances using the powershell cmdlet
What this does is pretty much what it says on the tin. The cmdlet takes two objects and compares them based on a input property (in this case it’ll be database names).
Here’s the code: –
$InstanceA = '' $InstanceB = '' $SqlQuery = 'SELECT name FROM sys.databases' $DatabasesA = Invoke-SqlCmd2 -sqlinstance $InstanceA -query $SqlQuery $DatabasesB = Invoke-SqlCmd2 -SqlInstance $InstanceB -query $SqlQuery Compare-Object -ReferenceObject $DatabasesA -DifferenceObject $DatabasesB -Property "name"
Let’s run a quick test to show the output. Say I have two SQL instances with the following databases: –
If I run the script, I will get the following: –
This is telling me that Databases C & G exist in Instance B but not Instance A and that Databases E & I exist in Instance A but not in Instance B.
The script runs very quickly (even with a large amount of dbs) and gives a nice, easy to understand output that allowed me to work out which databases needed to be reseeded in my AG.
Of course, the $SqlQuery variable can be changed so that it can return other properties of the instances for comparison so this really is a nice way to compare two SQL instances.
Thanks for reading!