Automate schema comparisons with PowerShell
Last modified: March 28, 2025
The topic provides a detailed, step-by-step guide to setting up an automated process for schema comparison between a local scripts folder and a remote database. The provided workflow offers an automated solution for database specialists to efficiently and reliably deliver database changes. Specifically, it caters to scenarios where a database specialist is working on a local copy of the database and needs to regularly synchronize schema changes with a remote database. By implementing this workflow, the need for manual involvement in delivering schema changes is minimized.
How to set up automatic schema comparison with subsequent emailing of the results
The suggested automation solution involves a PowerShell script that initiates the comparison of the local scripts folder and a remote database. If any differences are detected between the source and target databases, a synchronization script is automatically sent via email, while a comparison report and log file are saved to the specified folders. The database specialist can execute the received script to update the remote database with the latest schema changes, ensuring everyone operates with the most up-to-date version. If a comparison error occurs, an email notification is sent to the designated email address, allowing for efficient problem resolution. In cases where no differences exist between the scripts folder and database, the database specialist receives an email confirming the databases are identical, and the relevant log file and report are stored in designated folders.
Prerequisites
- Installed and configured SMTP server
- Database scripts folder linked to a remote repository
Workflow
Step 1. Create a text file with the database connection details
Step 2. Create a PowerShell script file to run the job
Step 3. Optional: Schedule the PowerShell script execution
Step 4. Run the PowerShell file
Create a text file with the database connection details
1. Open any text editor application and enter the server connection, database name, authentication type, username, and password in a single line separated by commas.
User, Database, Server, Port, Password
In the provided example:
User
is the username you can use to establish the connection to the server.Database
is the name of the database you want to connect.Server
is the name of the required server.Port
is the port number of the server.password
is the password.
For example,
root,bikestoresdev,mysql,3306,password
2. Save the file.
Create a PowerShell script file to run the job
At this stage, you need to create a PowerShell script that performs a comparison between the scripts folder and the database. The script should send an informative email indicating whether the scripts folder and the database are identical, different, or if there is an error based on the comparison result. If differences are found, the script should attach a synchronization script to the email.
To create a PowerShell script file:
1. Open a text editor or PowerShell Integrated Scripting Environment (ISE).
2. Enter PowerShell commands in the editor.
Click to open the PowerShell script example
#load the library before executing the script
#[System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
#region Variables
$rootFolder = "D:\Monitor"
$databasesTxtPath = "D:\Monitor\Databases.txt"
#Declare $diffToolLocation variable for dbForge Schema Compare for MySQL
$diffToolLocation = "C:\Program Files\Devart\dbForge Studio for MySQL\dbforgemysql.com"
#endregion
#region SC Variables
foreach ($line in [System.IO.File]::ReadAllLines($databasesTxtPath)) {
# Read the connection parameters for the current database from the configuration file
$userName = ($line -split ",")[0]
$database = ($line -split ",")[1]
$server = ($line -split ",")[2]
$port = ($line -split ",")[3]
$password = ($line -split ",")[4]
$today = (Get-Date -Format "dd-MM-yyyy_HH_MM_ss")
$DiffScriptLocation = New-Item -ItemType Directory -Force -Path ($rootFolder + "\" + "DiffSсript")
$ReportsLocation = New-Item -ItemType Directory -Force -Path ($rootFolder + "\" + "DiffReports")
$logsLocation = New-Item -ItemType Directory -Force -Path ($rootFolder + "\" + "Logs")
$srvCleanName = ($server -replace "\\", "")
$CurrentSF = "`"D:\Monitor\ScriptFolder`" serverversion:`"8.2.0;MySql`" collation:`"latin1_swedish_ci`""
$currentReportFile = Join-Path $ReportsLocation "$srvCleanName.$database.$today"
$logName = Join-Path $logsLocation "$srvCleanName.$database.$today.txt"
$diffScript = Join-Path $DiffScriptLocation "$srvCleanName.$database.$today.sql"
#endregion
#region Mail Variables
# Define SMTP Server and port
$SmtpServer = "smtp.office365.com"
$SmtpPort = "587"
# Define email data
$EmailFrom = "[email protected]"
$EmailTo = "[email protected]"
$EmailSubject = "Result of Comparison of your Script Folder with " + $database
#$EmailBody = "This is a test email."
# Define credentials (Make sure to replace 'myusername' and 'mypassword' with your actual Office365 username and password)
$MailUsername = "[email protected]"
$MailPassword = ConvertTo-SecureString "[password]" -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $MailUsername, $MailPassword
# Send the email
#Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $EmailSubject -Body $EmailBody -SmtpServer $SmtpServer -port $SmtpPort -UseSsl -Credential $Credentials
#endregion
Write-Host "Server: $server; Database: $database; Port: $port"
# Create a database connection
$connectionString = "User ID=$userName;Server=$server;Port=$port;Password=$password;"
$TargetConnectionString = "User ID=$userName;Database=$database;Server=$server;Port=$port;Password=$password;"
# Test the database connection
Write-Host "Testing the database connection..."
# $connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
$connection = New-Object MySql.Data.MySqlClient.MySqlConnection($connectionString)
try {
$connection.Open()
Write-Host "Connection successful"
}
catch { Write-Host "Connection failed: $($_.Exception.Message)" }
finally { $connection.Close() }
# Log information about checking the database
New-Item -ItemType File -Force -Path $logName
# Compare
$process = Start-Process -FilePath $diffToolLocation -ArgumentList "/schemacompare /source scriptsfolder:$CurrentSF /target connection:`"$TargetConnectionString`" /report:`"$currentReportFile`" /reportformat:html /includeobjects:All /log:`"$logName`" /sync:`"$diffScript`"" -PassThru -Wait -windowstyle hidden
#Write-Output "ExitCode:" $process.ExitCode
# Return exit code 100 in case the databases are identical
if ($process.ExitCode -eq 100 -and !(Test-Path $diffScript) ) {
Add-Content -Path $logName -Value "Your scripts folder and database are identical"
# Send the email
$EmailBody = "Scripts Folder and database are identical. Database for Comparison: " + $database
Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $EmailSubject -Body $EmailBody -SmtpServer $SmtpServer -port $SmtpPort -UseSsl -Credential $Credentials
#remove the newly created report, since no differences are detected
#Remove-Item -Path $currentReportFile".html" -Force:$true -Confirm:$false
continue
}
# Return exit code 101 in case the databases are not identical
if ($process.ExitCode -eq 0 -and (Test-Path $diffScript)) {
Add-Content -Path $logName -Value "Your scripts folder and database are not identical"
# Send the email
$EmailBody = "Scripts Folder and database are not identical. Database for Comparison: " + $database
Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $EmailSubject -Body $EmailBody -SmtpServer $SmtpServer -port $SmtpPort -UseSsl -Credential $Credentials -Attachments $diffScript
#remove the newly created report, since no differences are detected
#Remove-Item -Path $currentReportFile".html" -Force:$true -Confirm:$false
continue
}
else {
$EmailSubject = "Something went wrong during Comparison of your script folder with " + $database
# Send the email
$EmailBody = "During Comparison of your Script Folder with " + $database + " we got an exit code: " + $process.ExitCode
Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $EmailSubject -Body $EmailBody -SmtpServer $SmtpServer -port $SmtpPort -UseSsl -Credential $Credentials
continue
}
}
Note
Customize the variables in the provided script to match your project’s specific requirements.
3. Save the file with a .ps1 extension (e.g., myscript.ps1).
The provided PowerShell script is developed to use Schema Compare exit codes for its logic.
-
If the tool detects that the databases are identical and returns exit code 100, the script sends an email with a message stating: “Your script folder and database are identical” to the specified email address. A comparison report and a log file are also generated and saved to the designated folders.
-
If the databases are not identical and the tool returns exit code 101, the script generates a synchronization script. It attaches the sync script to an email with the message: “Your script folder and database are not identical.” In this case, a comparison report and a log file are also generated.
-
If any other exit code is returned, indicating an error during the comparison of the script folder with the database, the script sends an email with the message: “Something went wrong during the comparison of your script folder with the database.” The script also creates and saves a log file to the designated location.
Note
You can customize the script to associate its actions with other exit codes. Refer to the Exit codes used in the command line documentation topic to see the list of all Schema Compare’s exit codes.
Optional: Schedule the PowerShell script execution
The execution of the PowerShell script can be scheduled using task scheduler programs, such as Windows Task Scheduler, which is available on most Windows operating systems.
To schedule the PowerShell script using Windows Task Scheduler, you can follow these general steps:
-
Open the Control Panel > Administrative Tools and select Task Scheduler.
-
In the Task Scheduler window that opens, navigate to the Actions pane and click Create Basic Task to create a scheduled task.
-
In the Create Basic Task Wizard window that opens, specify the name and description of the task and click Next.
-
On the Trigger page, choose when to launch the task and click Next.
-
On the Action page, click Start a program to schedule a program to start automatically and click Next.
-
On the Start a Program page, click Browse to select the .ps1 file you have created and click Next.
-
On the Finish page, verify the settings and click Finish.
The task will be displayed in the Active Tasks section of Windows Task Scheduler.
Run the PowerShell file
To conduct a comprehensive evaluation of the scenario, we will simulate three distinct situations: the first, where the scripts folder and the database are identical; the second, where differences exist between the two; and the third, where a comparison error arises during the process.
Case 1: No differences between the scripts folder and the database
In this case, after running the PowerShell Script, we receive an email confirming that the databases are identical.
We also check the report folder and find that the comparison report has been successfully generated and saved to the specified location. The log file has also been generated.
The diffs report is generated in the HTML format. If you require a different format, you can specify it within the PowerShell script. Excel and XML are also available as options for generating the comparison report.
Case 2: The scripts folder and the database are different
In this scenario, we simulate differences between the local scripts folder and a remote database. After executing the script, we receive an email containing the synchronization script as an attachment.
The comparison report and log file are also generated and saved to the specified locations.
Case 3: An error occurs during the synchronization process
In this scenario, we deliberately introduce an error during the comparison process between the scripts folder and the database. Upon running the script, we receive an email notification stating that an issue occurred with the comparison.
The log file is saved to the Logs folder.
Explore more
Configure the schema comparison logs email delivery
Discover how to configure automatic email delivery of the log file for both successful and failed SQL schema comparisons.
Compare schemas in multiple databases from the command line
Find out how to automate and schedule the daily comparison and synchronization operations of multiple databases using the command line.
How to set up automatic log sending in the event of a comparison error
Learn how to configure the automatic email delivery of the schema comparison log file specifically for cases where the comparison encounters failures.
- Automate schema comparisons with PowerShell
- How to set up automatic schema comparison with subsequent emailing of the results
- Create a text file with the database connection details
- Create a PowerShell script file to run the job
- Optional: Schedule the PowerShell script execution
- Run the PowerShell file
- Explore more