Powershell Script to Add New Database to Existing Availability Groups

One of the common tasks for DBA to add the new database to existing availability groups. This can be done fairly easy via SSMS. The requirement is how to deploy the new database from Team Foundation Server (TFS) to SQL Server Alway on AG listener and automatically add this database to Availability groups. Here is the script written for this purpose. I have used powershell as this one of the tool which is very useful and easy way to automate from TFS.

 Write-host "Adding Database to existing Availability Groups"

$BackupLocation = "Provide the shared location where both nodes can access"
$dbName = "DatabaseName"
$ListenerName = "AGListener"

$ListReplicaNames = Invoke-Sqlcmd -Query "SELECT name, replica_server_name, role_desc FROM master.sys.availability_replicas as AR
INNER JOIN master.sys.dm_hadr_availability_replica_states as ARS ON AR.replica_id = ARS.replica_id
INNER JOIN master.sys.availability_groups as AG ON AR.group_id = AG.group_id" -ServerInstance $ListenerName
$replica1 = $ListReplicaNames | Where-Object {$_.role_desc -eq "PRIMARY"}
$replica2 = $ListReplicaNames | Where-Object {$_.role_desc -eq "SECONDARY"}
$server1 = $replica1.replica_server_name
$server2 = $replica2.replica_server_name
$AGName = $replica1.name


#Create Backup of DB node 1
$bakPath = $BackupLocation + $dbName + "_" + $dateStamp + ".bak"
$trnPath = $BackupLocation + $dbName + "_" + $dateStamp + ".trn"

set-location "SQLSERVER:\SQL\$server1\Databases"
Write-Host "Backing up $server1 $dbName to $bakPath"
Backup-SqlDatabase -database $dbName -backupFile $bakPath
Write-Host " ... backup complete"

Write-Host "Backing up $server1 $dbName to $trnPath"
Backup-SqlDatabase -Database $dbName -BackupFile $trnPath -BackupAction Log
Write-Host " ... backup complete"

#Resotore Backup of DB in node 2
set-location "SQLSERVER:\SQL\$server2\Databases"
Write-Host "Restoring $server2 $dbName from $bakPath"
Restore-SqlDatabase -Database $dbName -BackupFile $bakPath -ServerInstance $server2 -NoRecovery
Write-Host " ... restoring complete"

Write-Host "Restoring $server2 $dbName from $trnPath"
Restore-SqlDatabase -Database $dbName -BackupFile $trnPath -ServerInstance $server2 -RestoreAction Log -NoRecovery
Write-Host " ... restoring complete"
#Add Database in AvailabilityGroups
Write-Host "Add database: $dbName to availability group: $AGName"
Add-SqlAvailabilityDatabase -Path SQLSERVER:\Sql\$server1\AvailabilityGroups\$AGName\AvailabilityDatabases -Database $dbName
Add-SqlAvailabilityDatabase -Path SQLSERVER:\Sql\$server2\AvailabilityGroups\$AGName\AvailabilityDatabases -Database $dbName
Write-Host " Database $dbname has been added"
$ErrorMessage = $_.Exception.Message
Write-Host $ErrorMessage
# This will write the execution time logged in the AddDBToAG.log file
"This script executed at $Time" | out-file D:\logs\AddDBToAG.log -append



Hope you enjoyed the post!


Ramasankar Molleti

LinkedIn: LinkedIn Profile

Twitter: Twitter




About Ramasankar

My name is Ramasankar Molleti, and I have been working on various database systems (SQL Server, Oracle, Postgres, DynamoDB, Redshift) over 10 years, primarily focusing on Database Administration, Architect , Development and Business intelligence. I also have working experience on Amazon Web Services DevOps. I hold various Microsoft certifications (Microsoft Certified Information Technology Professional, Microsoft Certified Technology Specialist, and Microsoft Certified Solution Associate). Disclaimer The views expressed on this website/blog are mine alone and do not reflect the views of my company. All postings on this blog are provided “AS IS” with no warranties, and confers no rights. The owner of https://sqlram.wordpress.com will not be liable for any errors or omissions in this information nor for the availability of this information. The owner will not be liable for any losses, injuries, or damages from the display or use of this information.
This entry was posted in Always On Availability Groups, Database Administration, Powershell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s