Menggunakan PowerShell untuk menyinkronkan data pada beberapa database di Microsoft Azure SQL Database
Berlaku untuk:Azure SQL Database
Contoh Azure PowerShell ini mengonfigurasi Sinkronisasi Data SQL untuk menyinkronkan data pada beberapa database di Azure SQL Database.
Jika Anda tidak memiliki langganan Azure, buat akun Azure gratis sebelum memulai.
Catatan
Artikel ini menggunakan modul Azure Az PowerShell, yang merupakan modul PowerShell yang direkomendasikan untuk berinteraksi dengan Azure. Untuk mulai menggunakan modul Az PowerShell, lihat Menginstal Azure PowerShell. Untuk mempelajari cara bermigrasi ke modul Az PowerShell, lihat Memigrasikan Azure PowerShell dari AzureRM ke Az.
Menggunakan Azure Cloud Shell
Azure meng-hosting Azure Cloud Shell, lingkungan shell interaktif yang dapat Anda gunakan melalui browser. Anda dapat menggunakan Bash atau PowerShell dengan Cloud Shell untuk bekerja dengan layanan Azure. Anda dapat menggunakan perintah Cloud Shell yang telah diinstal sebelumnya untuk menjalankan kode dalam artikel ini tanpa harus menginstal apa-apa di lingkungan lokal Anda.
Untuk memulai Azure Cloud Shell:
Opsi | Contoh/Tautan |
---|---|
Pilih Coba di sudut kanan atas blok kode. Memilih Coba tidak secara otomatis menyalin kode ke Cloud Shell. | |
Buka https://shell.azure.com, atau pilih tombol Luncurkan Cloud Shell untuk membuka Cloud Shell di browser Anda. | |
Pilih tombol Cloud Shell pada bilah menu di kanan atas di portal Microsoft Azure. |
Untuk menjalankan kode dalam artikel ini di Azure Cloud Shell:
Mulai Cloud Shell.
Pilih tombol Salin pada blok kode untuk menyalin kode.
Tempelkan kode tersebut ke sesi Cloud Shell dengan memilih Ctrl+Shift+V untuk Windows dan Linux, atau dengan memilih Cmd+Shift+V untuk macOS.
Pilih Enter untuk menjalankan kode.
Jika Anda memilih untuk memasang dan menggunakan PowerShell secara lokal, tutorial ini memerlukan Az PowerShell 1.4.0 atau yang lebih baru. Jika Anda perlu peningkatan, lihat Instal modul Azure PowerShell. Jika Anda menjalankan PowerShell secara lokal, Anda juga perlu menjalankan Connect-AzAccount
untuk membuat koneksi dengan Azure.
Untuk gambaran umum sinkronisasi data SQL, lihat Menyinkronkan data di beberapa database awan dan lokal dengan Sinkronisasi Data SQL di Azure.
Penting
SQL Data Sync tidak mendukung Azure SQL Managed Instance pada saat ini.
Prasyarat
- Buat database di Azure SQL Database dai sampel database AdventureWorksLT sebagai database hub.
- Buat database di Azure SQL Database di wilayah yang sama dengan database sinkronisasi.
- Perbarui placeholder parameter sebelum menjalankan contoh.
Contoh
using namespace Microsoft.Azure.Commands.Sql.DataSync.Model
using namespace System.Collections.Generic
# hub database info
$subscriptionId = "<subscriptionId>"
$resourceGroupName = "<resourceGroupName>"
$serverName = "<serverName>"
$databaseName = "<databaseName>"
# sync database info
$syncDatabaseResourceGroupName = "<syncResourceGroupName>"
$syncDatabaseServerName = "<syncServerName>"
$syncDatabaseName = "<syncDatabaseName>"
# sync group info
$syncGroupName = "<syncGroupName>"
$conflictResolutionPolicy = "HubWin" # can be HubWin or MemberWin
$intervalInSeconds = 300 # sync interval in seconds (must be no less than 300)
# member database info
$syncMemberName = "<syncMemberName>"
$memberServerName = "<memberServerName>"
$memberDatabaseName = "<memberDatabaseName>"
$memberDatabaseType = "SqlServerDatabase" # can be AzureSqlDatabase or SqlServerDatabase
$syncDirection = "Bidirectional" # can be Bidirectional, Onewaymembertohub, Onewayhubtomember
# sync agent info
$syncAgentName = "<agentName>"
$syncAgentResourceGroupName = "<syncAgentResourceGroupName>"
$syncAgentServerName = "<syncAgentServerName>"
$syncMemberResourceId = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Sql/servers/$serverName/databases/$syncMemberDBName"
# temp file to save the sync schema
$tempFile = $env:TEMP+"\syncSchema.json"
# list of included columns and tables in quoted name
$includedColumnsAndTables = "[SalesLT].[Address].[AddressID]",
"[SalesLT].[Address].[AddressLine2]",
"[SalesLT].[Address].[rowguid]",
"[SalesLT].[Address].[PostalCode]",
"[SalesLT].[ProductDescription]"
$metadataList = [System.Collections.ArrayList]::new($includedColumnsAndTables)
Connect-AzAccount
Select-AzSubscription -SubscriptionId $subscriptionId
# use if it's safe to show password in script, otherwise use PromptForCredential
# $user = "username"
# $password = ConvertTo-SecureString -String "password" -AsPlainText -Force
# $credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $user, $password
$credential = $Host.ui.PromptForCredential("Need credential",
"Please enter your user name and password for server "+$serverName+".database.windows.net",
"",
"")
# create a new sync group (if you use private link, make sure to manually approve it)
Write-Host "Creating Sync Group "$syncGroupName"..."
New-AzSqlSyncGroup -ResourceGroupName $resourceGroupName -ServerName $serverName -DatabaseName $databaseName -Name $syncGroupName `
-SyncDatabaseName $syncDatabaseName -SyncDatabaseServerName $syncDatabaseServerName -SyncDatabaseResourceGroupName $syncDatabaseResourceGroupName `
-ConflictResolutionPolicy $conflictResolutionPolicy -DatabaseCredential $credential -UsePrivateLinkConnection | Format-list
# use if it's safe to show password in script, otherwise use PromptForCredential
# $user = "username"
# $password = ConvertTo-SecureString -String "password" -AsPlainText -Force
# $credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $user, $password
$credential = $Host.ui.PromptForCredential("Need credential",
"Please enter your user name and password for server "+$serverName+".database.windows.net",
"",
"")
# add a new sync member (if you use private link, make sure to manually approve it)
Write-Host "Adding member"$syncMemberName" to the sync group..."
New-AzSqlSyncMember -ResourceGroupName $resourceGroupName -ServerName $serverName -DatabaseName $databaseName `
-SyncGroupName $syncGroupName -Name $syncMemberName -MemberDatabaseType $memberDatabaseType -SyncAgentResourceGroupName $syncAgentResourceGroupName `
-SyncAgentServerName $syncAgentServerName -SyncAgentName $syncAgentName -SyncDirection $syncDirection -SqlServerDatabaseID $syncAgentInfo.DatabaseId `
-SyncMemberAzureDatabaseResourceId $syncMemberResourceId -UsePrivateLinkConnection | Format-list
# update existing sync member to use private link connection
Update-AzSqlSyncMember `
-ResourceGroupName $resourceGroupName -ServerName $serverName -DatabaseName $databaseName -SyncGroupName $syncGroupName -Name $syncMemberName `
-MemberDatabaseCredential $memberDatabaseCredential -SyncMemberAzureDatabaseResourceId $syncMemberResourceId -UsePrivateLinkConnection $true
# update existing sync group and remove private link connection
Update-AzSqlSyncGroup `
-ResourceGroupName $resourceGroupName -ServerName $serverName -DatabaseName $databaseName -Name $syncGroupName -UsePrivateLinkConnection $false
# run the following Get-AzSqlSyncGroup/ Get-AzSqlSyncMember commands to confirm that a private link has been setup for Data Sync, if you decide to use private link.
# Get-AzSqlSyncMember returns information about one or more Azure SQL Database Sync Members. Specify the name of a sync member to see information for only that sync member.
Get-AzSqlSyncMember `
-ResourceGroupName $resourceGroupName -ServerName $serverName -DatabaseName $databaseName -SyncGroupName $syncGroupName -Name $syncMemberName ` | Format-List
# Get-AzSqlSyncGroup returns information about one or more Azure SQL Database Sync Groups. Specify the name of a sync group to see information for only that sync group.
Get-AzSqlSyncGroup `
-ResourceGroupName $resourceGroupName -ServerName $serverName -DatabaseName $databaseName ` | Format-List
# approve private endpoint connection, if you decide to use private link
Approve-AzPrivateEndpointConnection `
-Name myPrivateEndpointConnection -ResourceGroupName myResourceGroup -ServiceName myPrivateLinkService
# refresh database schema from hub database, specify the -SyncMemberName parameter if you want to refresh schema from the member database
Write-Host "Refreshing database schema from hub database..."
$startTime = Get-Date
Update-AzSqlSyncSchema -ResourceGroupName $resourceGroupName -ServerName $serverName -DatabaseName $databaseName -SyncGroupName $syncGroupName
# waiting for successful refresh
$startTime = $startTime.ToUniversalTime()
$timer=0
$timeout=90
# check the log and see if refresh has gone through
Write-Host "Check for successful refresh..."
$isSucceeded = $false
while ($isSucceeded -eq $false) {
Start-Sleep -s 10
$timer=$timer+10
$details = Get-AzSqlSyncSchema -SyncGroupName $syncGroupName -ServerName $serverName -DatabaseName $databaseName -ResourceGroupName $resourceGroupName
if ($details.LastUpdateTime -gt $startTime) {
Write-Host "Refresh was successful"
$isSucceeded = $true
}
if ($timer -eq $timeout) {
Write-Host "Refresh timed out"
break;
}
}
# get the database schema
Write-Host "Adding tables and columns to the sync schema..."
$databaseSchema = Get-AzSqlSyncSchema -ResourceGroupName $ResourceGroupName -ServerName $ServerName `
-DatabaseName $DatabaseName -SyncGroupName $SyncGroupName `
$databaseSchema | ConvertTo-Json -depth 5 -Compress | Out-File "C:\Users\OnPremiseServer\AppData\Local\Temp\syncSchema.json"
$newSchema = [AzureSqlSyncGroupSchemaModel]::new()
$newSchema.Tables = [List[AzureSqlSyncGroupSchemaTableModel]]::new();
# add columns and tables to the sync schema
foreach ($tableSchema in $databaseSchema.Tables) {
$newTableSchema = [AzureSqlSyncGroupSchemaTableModel]::new()
$newTableSchema.QuotedName = $tableSchema.QuotedName
$newTableSchema.Columns = [List[AzureSqlSyncGroupSchemaColumnModel]]::new();
$addAllColumns = $false
if ($MetadataList.Contains($tableSchema.QuotedName)) {
if ($tableSchema.HasError) {
$fullTableName = $tableSchema.QuotedName
Write-Host "Can't add table $fullTableName to the sync schema" -foregroundcolor "Red"
Write-Host $tableSchema.ErrorId -foregroundcolor "Red"
continue;
}
else {
$addAllColumns = $true
}
}
foreach($columnSchema in $tableSchema.Columns) {
$fullColumnName = $tableSchema.QuotedName + "." + $columnSchema.QuotedName
if ($addAllColumns -or $MetadataList.Contains($fullColumnName)) {
if ((-not $addAllColumns) -and $tableSchema.HasError) {
Write-Host "Can't add column $fullColumnName to the sync schema" -foregroundcolor "Red"
Write-Host $tableSchema.ErrorId -foregroundcolor "Red"
}
elseif ((-not $addAllColumns) -and $columnSchema.HasError) {
Write-Host "Can't add column $fullColumnName to the sync schema" -foregroundcolor "Red"
Write-Host $columnSchema.ErrorId -foregroundcolor "Red"
}
else {
Write-Host "Adding"$fullColumnName" to the sync schema"
$newColumnSchema = [AzureSqlSyncGroupSchemaColumnModel]::new()
$newColumnSchema.QuotedName = $columnSchema.QuotedName
$newColumnSchema.DataSize = $columnSchema.DataSize
$newColumnSchema.DataType = $columnSchema.DataType
$newTableSchema.Columns.Add($newColumnSchema)
}
}
}
if ($newTableSchema.Columns.Count -gt 0) {
$newSchema.Tables.Add($newTableSchema)
}
}
# convert sync schema to JSON format
$schemaString = $newSchema | ConvertTo-Json -depth 5 -Compress
# work around a PowerShell bug
$schemaString = $schemaString.Replace('"Tables"', '"tables"').Replace('"Columns"', '"columns"').Replace('"QuotedName"', '"quotedName"').Replace('"MasterSyncMemberName"','"masterSyncMemberName"')
# save the sync schema to a temp file
$schemaString | Out-File $tempFile
# update sync schema
Write-Host "Updating the sync schema..."
Update-AzSqlSyncGroup -ResourceGroupName $resourceGroupName -ServerName $serverName `
-DatabaseName $databaseName -Name $syncGroupName -Schema $tempFile
$syncLogStartTime = Get-Date
# trigger sync manually
Write-Host "Trigger sync manually..."
Start-AzSqlSyncGroupSync -ResourceGroupName $resourceGroupName -ServerName $serverName -DatabaseName $databaseName -SyncGroupName $syncGroupName
# check the sync log and wait until the first sync succeeded
Write-Host "Check the sync log..."
$isSucceeded = $false
for ($i = 0; ($i -lt 300) -and (-not $isSucceeded); $i = $i + 10) {
Start-Sleep -s 10
$syncLogEndTime = Get-Date
$syncLogList = Get-AzSqlSyncGroupLog -ResourceGroupName $resourceGroupName -ServerName $serverName -DatabaseName $databaseName `
-SyncGroupName $syncGroupName -StartTime $syncLogStartTime.ToUniversalTime() -EndTime $syncLogEndTime.ToUniversalTime()
if ($synclogList.Length -gt 0) {
foreach ($syncLog in $syncLogList) {
if ($syncLog.Details.Contains("Sync completed successfully")) {
Write-Host $syncLog.TimeStamp : $syncLog.Details
$isSucceeded = $true
}
}
}
}
if ($isSucceeded) {
# enable scheduled sync
Write-Host "Enable the scheduled sync with 300 seconds interval..."
Update-AzSqlSyncGroup -ResourceGroupName $resourceGroupName -ServerName $serverName -DatabaseName $databaseName `
-Name $syncGroupName -IntervalInSeconds $intervalInSeconds
}
else {
# output all log if sync doesn't succeed in 300 seconds
$syncLogEndTime = Get-Date
$syncLogList = Get-AzSqlSyncGroupLog -ResourceGroupName $resourceGroupName -ServerName $serverName -DatabaseName $databaseName `
-SyncGroupName $syncGroupName -StartTime $syncLogStartTime.ToUniversalTime() -EndTime $syncLogEndTime.ToUniversalTime()
if ($synclogList.Length -gt 0) {
foreach ($syncLog in $syncLogList) {
Write-Host $syncLog.TimeStamp : $syncLog.Details
}
}
}
Bersihkan penyebaran
Setelah menjalankan sampel skrip, Anda dapat menjalankan perintah berikut untuk menghapus grup sumber daya dan semua sumber daya yang terkait.
Remove-AzResourceGroup -ResourceGroupName $ResourceGroupName
Remove-AzResourceGroup -ResourceGroupName $SyncDatabaseResourceGroupName
Penjelasan skrip
Skrip ini menggunakan perintah berikut. Setiap perintah dalam tabel ditautkan ke dokumentasi spesifik-perintah.
Perintah | Catatan |
---|---|
New-AzSqlSyncAgent | Membuat Agen Sinkronisasi baru. |
New-AzSqlSyncAgentKey | Membuat kunci agen yang terkait dengan Agen Sinkronisasi. |
Get-AzSqlSyncAgentLinkedDatabase | Mendapatkan semua informasi untuk Agen Sinkronisasi. |
New-AzSqlSyncMember | Menambahkan anggota baru ke grup sinkronisasi. |
Update-AzSqlSyncSchema | Merefresh informasi skema database. |
Get-AzSqlSyncSchema | Mendapatkan informasi skema database. |
Update-AzSqlSyncGroup | Memperbarui grup sinkronisasi. |
Start-AzSqlSyncGroupSync | Memicu sinkronisasi. |
Get-AzSqlSyncGroupLog | Memeriksa Log Sinkronisasi. |
Langkah berikutnya
Untuk informasi selengkapnya tentang Azure PowerShell, lihat Dokumentasi Microsoft Azure PowerShell.
Sampel skrip PowerShell tambahan dapat ditemukan di skrip PowerShell Azure SQL Database.
Untuk informasi selengkapnya tentang SQL Data Sync, lihat:
- Tutorial: Membuat pengguna Azure AD menggunakan aplikasi Azure AD
- Menyiapkan Sinkronisasi Data
- Menggunakan portal Microsoft Azure - Tutorial: Menyiapkan Sinkronisasi Data SQL untuk menyinkronkan data antara Microsoft Azure SQL Database dan SQL Server
- Menggunakan PowerShell - Gunakan PowerShell untuk menyinkronkan data pada database di Azure SQL Database dan SQL Server
- Data Sync Agent - Data Sync Agent untuk SQL Data Sync di Azure
- Praktik terbaik - Praktik terbaik untuk SQL Data Sync di Azure
- Memantau - Memantau SQL Data Sync dengan log Azure Monitor
- Memecahkan masalah - Memecahkan masalah dengan SQL Data Sync di Azure
- Memperbarui skema sinkronisasi
- Dengan Transact-SQL - Otomatiskan replikasi perubahan skema dalam Sinkronisasi Data SQL di Azure
- Gunakan PowerShell - Gunakan PowerShell untuk memperbarui skema sinkronisasi di grup sinkronisasi yang ada
Untuk informasi selengkapnya tentang SQL Database, lihat:
Saran dan Komentar
https://aka.ms/ContentUserFeedback.
Segera hadir: Sepanjang tahun 2024 kami akan menghentikan penggunaan GitHub Issues sebagai mekanisme umpan balik untuk konten dan menggantinya dengan sistem umpan balik baru. Untuk mengetahui informasi selengkapnya, lihat:Kirim dan lihat umpan balik untuk