forked from MrKruge/AzureSQLMigration
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAzSQL-Migration.ps1
More file actions
724 lines (602 loc) · 25.3 KB
/
AzSQL-Migration.ps1
File metadata and controls
724 lines (602 loc) · 25.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
<#
.SYNOPSIS
Azure SQL Database replication and migration script using az cli.
.DESCRIPTION
Creates a geo-replica, deletes the replication link, handles database renaming
with _old suffix, and migrates permissions from source to target database.
.PARAMETER RsgSource
Source resource group name
.PARAMETER RsgTarget
Target resource group name
.PARAMETER SqlSource
Source SQL server name
.PARAMETER SqlTarget
Target SQL server name
.PARAMETER DbSource
Source database name
.PARAMETER DbTarget
Target database name (final name on target server)
.PARAMETER SubSource
Source subscription ID or name
.PARAMETER SubTarget
Target subscription ID or name
.PARAMETER ElasticPool
Optional: Target elastic pool name
.PARAMETER MigratePermissions
Switch: Migrate database permissions from source to target
.PARAMETER PermissionsSourceDatabase
Optional: Database to retrieve permissions from (defaults to source database).
Use this when you want to get permissions from a different database than the source.
.PARAMETER KeyVaultName
Optional: Azure Key Vault name for retrieving SQL credentials (default: actt01-data-sdc-orch-kv)
.PARAMETER KeyVaultSecretName
Optional: Key Vault secret name containing the SQL password (default: act-tg-azure)
.PARAMETER KeyVaultSubscription
Optional: Subscription ID or name where the Key Vault is located (if different from source/target subscriptions)
.PARAMETER SqlLoginName
Optional: SQL Login/User name to set password for (default: Azure)
.EXAMPLE
.\AzSQL-Migration.ps1 `
-RsgSource "source-resource-group" `
-RsgTarget "target-resource-group" `
-SqlSource "source-sql-server" `
-SqlTarget "target-sql-server" `
-DbSource "SourceDatabase" `
-DbTarget "TargetDatabase_DEV" `
-SubSource "source-subscription-name" `
-SubTarget "00000000-0000-0000-0000-000000000000"
.EXAMPLE
.\AzSQL-Migration.ps1 `
-RsgSource "source-resource-group" `
-RsgTarget "target-resource-group" `
-SqlSource "source-sql-server" `
-SqlTarget "target-sql-server" `
-DbSource "SourceDatabase" `
-DbTarget "TargetDatabase_PRD" `
-SubSource "source-subscription-name" `
-SubTarget "00000000-0000-0000-0000-000000000000" `
-ElasticPool "target-elastic-pool" `
-MigratePermissions
.EXAMPLE
.\AzSQL-Migration.ps1 `
-RsgSource "source-resource-group" `
-RsgTarget "target-resource-group" `
-SqlSource "source-sql-server" `
-SqlTarget "target-sql-server" `
-DbSource "SourceDatabase" `
-DbTarget "TargetDatabase_PRD" `
-SubSource "source-subscription-name" `
-SubTarget "00000000-0000-0000-0000-000000000000" `
-ElasticPool "target-elastic-pool" `
-MigratePermissions `
-PermissionsSourceDatabase "PermissionsDatabase" `
-KeyVaultName "my-keyvault" `
-KeyVaultSecretName "sql-password-secret" `
-SqlLoginName "SqlLoginName"
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, HelpMessage="Source resource group name")]
[string]$RsgSource,
[Parameter(Mandatory=$true, HelpMessage="Target resource group name")]
[string]$RsgTarget,
[Parameter(Mandatory=$true, HelpMessage="Source SQL server name")]
[string]$SqlSource,
[Parameter(Mandatory=$true, HelpMessage="Target SQL server name")]
[string]$SqlTarget,
[Parameter(Mandatory=$true, HelpMessage="Source database name")]
[string]$DbSource,
[Parameter(Mandatory=$true, HelpMessage="Target database name (final name)")]
[string]$DbTarget,
[Parameter(Mandatory=$true, HelpMessage="Source subscription ID or name")]
[string]$SubSource,
[Parameter(Mandatory=$true, HelpMessage="Target subscription ID or name")]
[string]$SubTarget,
[Parameter(Mandatory=$false, HelpMessage="Target elastic pool name")]
[string]$ElasticPool = "",
[Parameter(Mandatory=$false, HelpMessage="Migrate permissions from source to target")]
[switch]$MigratePermissions,
[Parameter(Mandatory=$false, HelpMessage="Database to retrieve permissions from (defaults to source database)")]
[string]$PermissionsSourceDatabase = "",
[Parameter(Mandatory=$false, HelpMessage="Key Vault name for retrieving SQL credentials")]
[string]$KeyVaultName = "",
[Parameter(Mandatory=$false, HelpMessage="Key Vault secret name for SQL password")]
[string]$KeyVaultSecretName = "",
[Parameter(Mandatory=$false, HelpMessage="Key Vault subscription ID or name (if different from source/target)")]
[string]$KeyVaultSubscription = "",
[Parameter(Mandatory=$false, HelpMessage="SQL Login/User name to update password for")]
[string]$SqlLoginName = "Azure"
)
$ErrorActionPreference = "Stop"
#region Helper Functions
function Get-KeyVaultSecret {
<#
.SYNOPSIS
Retrieves a secret from Azure Key Vault
#>
param(
[string]$VaultName,
[string]$SecretName,
[string]$Subscription = ""
)
Write-Log "Retrieving secret '$SecretName' from Key Vault '$VaultName'..." "INFO"
try {
$kvArgs = @(
"keyvault", "secret", "show",
"--name", $SecretName,
"--vault-name", $VaultName,
"--query", "value",
"-o", "tsv",
"--only-show-errors"
)
if (-not [string]::IsNullOrWhiteSpace($Subscription)) {
$kvArgs += "--subscription", $Subscription
Write-Log "Using subscription: $Subscription" "INFO"
}
$secret = & az @kvArgs
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($secret)) {
throw "Failed to retrieve secret from Key Vault"
}
Write-Log "Successfully retrieved secret from Key Vault" "SUCCESS"
return $secret
}
catch {
Write-Log "Failed to retrieve secret '$SecretName' from Key Vault '$VaultName': $_" "ERROR"
throw
}
}
function Set-SqlUserPassword {
<#
.SYNOPSIS
Sets or updates the password for a SQL user/login
#>
param(
[string]$Server,
[string]$Database,
[string]$LoginName,
[string]$Password
)
Write-Log "Setting password for SQL user '$LoginName'..." "INFO"
$serverFqdn = "$Server.database.windows.net"
$accessToken = az account get-access-token --resource https://database.windows.net/ --query accessToken -o tsv
# Try to alter the user password first
$alterUserQuery = @"
IF EXISTS (SELECT * FROM sys.database_principals WHERE name = '$LoginName')
BEGIN
ALTER USER [$LoginName] WITH PASSWORD = '$Password'
PRINT 'Password updated for existing user'
END
ELSE
BEGIN
CREATE USER [$LoginName] WITH PASSWORD = '$Password'
PRINT 'User created with password'
END
"@
try {
$result = Invoke-Sqlcmd `
-ServerInstance $serverFqdn `
-Database $Database `
-Query $alterUserQuery `
-AccessToken $accessToken `
-ErrorAction Stop
Write-Log "Successfully set password for user '$LoginName'" "SUCCESS"
return $true
}
catch {
Write-Log "Failed to set password for user '$LoginName': $_" "WARNING"
Write-Log "Attempting to drop and recreate user..." "INFO"
# Try to drop and recreate the user
$recreateUserQuery = @"
IF EXISTS (SELECT * FROM sys.database_principals WHERE name = '$LoginName')
DROP USER [$LoginName]
CREATE USER [$LoginName] WITH PASSWORD = '$Password'
"@
try {
Invoke-Sqlcmd `
-ServerInstance $serverFqdn `
-Database $Database `
-Query $recreateUserQuery `
-AccessToken $accessToken `
-ErrorAction Stop
Write-Log "Successfully recreated user '$LoginName' with new password" "SUCCESS"
return $true
}
catch {
Write-Log "Failed to recreate user '$LoginName': $_" "ERROR"
return $false
}
}
}
function Write-Log {
<#
.SYNOPSIS
Writes formatted log messages with timestamp and color coding
#>
param(
[string]$Message,
[ValidateSet("INFO", "SUCCESS", "WARNING", "ERROR")]
[string]$Level = "INFO"
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$color = switch($Level) {
"ERROR" { "Red" }
"WARNING" { "Yellow" }
"SUCCESS" { "Green" }
default { "White" }
}
$output = "[$timestamp] [$Level] $Message"
if ($Level -eq "ERROR") {
Write-Host $output -ForegroundColor $color -ErrorAction Continue
} else {
Write-Host $output -ForegroundColor $color
}
}
function Test-DatabaseExists {
<#
.SYNOPSIS
Checks if a database exists on a SQL server
#>
param(
[string]$ResourceGroup,
[string]$Server,
[string]$Database,
[string]$Subscription
)
try {
$null = az sql db show `
--resource-group $ResourceGroup `
--server $Server `
--name $Database `
--subscription $Subscription `
--output none 2>$null
return $LASTEXITCODE -eq 0
}
catch {
return $false
}
}
function Get-DatabasePermissions {
<#
.SYNOPSIS
Extracts all database users and their role memberships using SqlServer module
#>
param(
[string]$ResourceGroup,
[string]$Server,
[string]$Database,
[string]$Subscription
)
Write-Log "Extracting permissions from source database..." "INFO"
# Check if SqlServer module is installed
if (-not (Get-Module -ListAvailable -Name SqlServer)) {
Write-Log "SqlServer PowerShell module not found. Installing..." "INFO"
try {
Install-Module -Name SqlServer -Scope CurrentUser -Force -AllowClobber -ErrorAction Stop
Write-Log "SqlServer module installed successfully" "SUCCESS"
}
catch {
Write-Log "Failed to install SqlServer module. Permission migration requires this module." "ERROR"
Write-Log "Please run: Install-Module -Name SqlServer -Scope CurrentUser -Force" "WARNING"
throw "SqlServer module installation failed"
}
}
Import-Module SqlServer -ErrorAction Stop
$query = @"
SELECT
dp.name AS UserName,
dp.type_desc AS UserType,
STRING_AGG(drole.name, ',') AS Roles
FROM sys.database_principals dp
LEFT JOIN sys.database_role_members drm ON dp.principal_id = drm.member_principal_id
LEFT JOIN sys.database_principals drole ON drm.role_principal_id = drole.principal_id
WHERE dp.type IN ('S', 'U', 'G', 'E', 'X')
AND dp.name NOT IN ('dbo', 'guest', 'INFORMATION_SCHEMA', 'sys', 'public')
AND dp.name NOT LIKE '##%'
GROUP BY dp.name, dp.type_desc
ORDER BY dp.name
"@
try {
# Use Azure AD authentication with Invoke-Sqlcmd
$serverFqdn = "$Server.database.windows.net"
Write-Log "Connecting to $serverFqdn/$Database using Azure AD authentication..." "INFO"
$result = Invoke-Sqlcmd `
-ServerInstance $serverFqdn `
-Database $Database `
-Query $query `
-AccessToken (az account get-access-token --resource https://database.windows.net/ --query accessToken -o tsv) `
-ErrorAction Stop
return $result
}
catch {
Write-Log "Failed to extract permissions: $_" "ERROR"
throw
}
}
function Set-DatabasePermissions {
<#
.SYNOPSIS
Applies user permissions and role memberships to target database
#>
param(
[string]$ResourceGroup,
[string]$Server,
[string]$Database,
[string]$Subscription,
[object[]]$Permissions
)
Write-Log "Applying permissions to target database..." "INFO"
$serverFqdn = "$Server.database.windows.net"
$accessToken = az account get-access-token --resource https://database.windows.net/ --query accessToken -o tsv
foreach ($user in $Permissions) {
$userName = $user.UserName
$userType = $user.UserType
$roles = if ($user.Roles) { $user.Roles -split ',' } else { @() }
Write-Log "Processing user: $userName" "INFO"
# Create user if it's an Azure AD (External) user
if ($userType -eq "EXTERNAL_USER") {
$createUserQuery = "IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = '$userName') CREATE USER [$userName] FROM EXTERNAL PROVIDER"
try {
Invoke-Sqlcmd `
-ServerInstance $serverFqdn `
-Database $Database `
-Query $createUserQuery `
-AccessToken $accessToken `
-ErrorAction Stop
Write-Log "Created user: $userName" "SUCCESS"
}
catch {
Write-Log "Failed to create user $userName : $_" "WARNING"
}
}
# Assign role memberships
foreach ($role in $roles) {
if ([string]::IsNullOrWhiteSpace($role)) { continue }
$roleQuery = "ALTER ROLE [$role] ADD MEMBER [$userName]"
try {
Invoke-Sqlcmd `
-ServerInstance $serverFqdn `
-Database $Database `
-Query $roleQuery `
-AccessToken $accessToken `
-ErrorAction Stop
Write-Log "Assigned role '$role' to $userName" "SUCCESS"
}
catch {
Write-Log "Failed to assign role '$role' to $userName : $_" "WARNING"
}
}
}
}
#endregion
#region Main Script
try {
Write-Log "==========================================" "INFO"
Write-Log "Azure SQL Database Migration Process" "INFO"
Write-Log "==========================================" "INFO"
Write-Log "Source: $SqlSource/$DbSource (Subscription: $SubSource)" "INFO"
Write-Log "Target: $SqlTarget/$DbTarget (Subscription: $SubTarget)" "INFO"
Write-Log "" "INFO"
# Step 1: Store permissions if requested
$sourcePermissions = $null
if ($MigratePermissions) {
# Determine which database and server to get permissions from
if ([string]::IsNullOrWhiteSpace($PermissionsSourceDatabase)) {
# Use source database on source server
$permissionsDb = $DbSource
$permissionsServer = $SqlSource
$permissionsRsg = $RsgSource
$permissionsSub = $SubSource
}
else {
# Use specified database on target server
$permissionsDb = $PermissionsSourceDatabase
$permissionsServer = $SqlTarget
$permissionsRsg = $RsgTarget
$permissionsSub = $SubTarget
}
Write-Log "Capturing database permissions from $permissionsServer/$permissionsDb..." "INFO"
try {
$sourcePermissions = Get-DatabasePermissions `
-ResourceGroup $permissionsRsg `
-Server $permissionsServer `
-Database $permissionsDb `
-Subscription $permissionsSub
Write-Log "Successfully captured permissions from $permissionsDb" "SUCCESS"
}
catch {
Write-Log "Failed to capture permissions: $_" "WARNING"
Write-Log "Continuing without permissions migration..." "WARNING"
$sourcePermissions = $null
}
}
# Step 2: Create geo-replica
Write-Log "Creating geo-replica on target server..." "INFO"
$replicaArgs = @(
"sql", "db", "replica", "create",
"--resource-group", $RsgSource,
"--server", $SqlSource,
"--name", $DbSource,
"--partner-server", $SqlTarget,
"--partner-resource-group", $RsgTarget,
"--subscription", $SubSource,
"--partner-sub-id", $SubTarget
)
if (-not [string]::IsNullOrWhiteSpace($ElasticPool)) {
$replicaArgs += "--elastic-pool", $ElasticPool
Write-Log "Using Elastic Pool: $ElasticPool" "INFO"
}
$replicaOutput = & az @replicaArgs 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) {
# Check if error is due to elastic pool storage limit
if ($replicaOutput -match "ElasticPoolOverStorage") {
Write-Log "Elastic pool storage limit reached. Checking for existing database to remove..." "WARNING"
# Switch to target subscription to check and delete database
az account set --subscription $SubTarget
if (Test-DatabaseExists -ResourceGroup $RsgTarget -Server $SqlTarget -Database $DbTarget -Subscription $SubTarget) {
Write-Log "Deleting existing database '$DbTarget' to free up storage..." "WARNING"
az sql db delete `
--resource-group $RsgTarget `
--server $SqlTarget `
--name $DbTarget `
--subscription $SubTarget `
--yes
if ($LASTEXITCODE -eq 0) {
Write-Log "Database '$DbTarget' deleted successfully" "SUCCESS"
Write-Log "Waiting 120 seconds for storage to be released..." "INFO"
Start-Sleep -Seconds 120
# Switch back to source subscription and retry replica creation
az account set --subscription $SubSource
Write-Log "Retrying geo-replica creation..." "INFO"
$replicaOutput = & az @replicaArgs 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) {
Write-Log "Replica creation output: $replicaOutput" "ERROR"
throw "Failed to create geo-replica after freeing storage"
}
} else {
throw "Failed to delete database '$DbTarget' to free storage"
}
} else {
Write-Log "Database '$DbTarget' does not exist. Cannot free storage." "ERROR"
Write-Log "Replica creation output: $replicaOutput" "ERROR"
throw "Elastic pool storage limit reached and no database to remove"
}
# Switch back to source subscription
az account set --subscription $SubSource
} else {
Write-Log "Replica creation output: $replicaOutput" "ERROR"
throw "Failed to create geo-replica"
}
}
Write-Log "Geo-replica created successfully" "SUCCESS"
# Wait for replication to sync
Write-Log "Waiting for replication to synchronize (30 seconds)..." "INFO"
Start-Sleep -Seconds 30
# Step 3: Delete replication link (promotes secondary to standalone)
Write-Log "Deleting replication link to promote secondary database..." "INFO"
az sql db replica delete-link `
--name $DbSource `
--resource-group $RsgSource `
--server $SqlSource `
--partner-server $SqlTarget `
--partner-resource-group $RsgTarget `
--subscription $SubSource `
--yes
if ($LASTEXITCODE -ne 0) {
throw "Failed to delete replication link"
}
Write-Log "Replication link deleted successfully" "SUCCESS"
# Small delay to ensure link is fully removed
Start-Sleep -Seconds 10
# Step 4: Handle database renaming on target
Write-Log "Handling database renaming on target server..." "INFO"
# Switch to target subscription
az account set --subscription $SubTarget
$oldDbName = ${DbTarget}
# Check if target database name already exists
if (Test-DatabaseExists -ResourceGroup $RsgTarget -Server $SqlTarget -Database $DbTarget -Subscription $SubTarget) {
Write-Log "Database '$DbTarget' already exists on target server" "INFO"
# Check if _old version exists and delete it
if (Test-DatabaseExists -ResourceGroup $RsgTarget -Server $SqlTarget -Database $oldDbName -Subscription $SubTarget) {
Write-Log "Deleting existing '$oldDbName'..." "INFO"
az sql db delete `
--resource-group $RsgTarget `
--server $SqlTarget `
--name $oldDbName `
--subscription $SubTarget `
--yes
Start-Sleep -Seconds 5
}
## # Rename current database to _old
## Write-Log "Renaming current '$DbTarget' to '$oldDbName'..." "INFO"
## az sql db rename `
## --resource-group $RsgTarget `
## --server $SqlTarget `
## --name $DbTarget `
## --new-name $oldDbName `
## --subscription $SubTarget
## Write-Log "Successfully renamed database to '$oldDbName'" "SUCCESS"
}
# Rename the replicated database to the target name
if ($DbSource -ne $DbTarget) {
Write-Log "Renaming replicated database from '$DbSource' to '$DbTarget'..." "INFO"
az sql db rename `
--resource-group $RsgTarget `
--server $SqlTarget `
--name $DbSource `
--new-name $DbTarget `
--subscription $SubTarget
Write-Log "Successfully renamed to '$DbTarget'" "SUCCESS"
}
else {
Write-Log "Database already has the target name: $DbTarget" "INFO"
}
# Step 5: Apply permissions to target database
if ($MigratePermissions -and $sourcePermissions) {
Write-Log "Migrating permissions to target database..." "INFO"
try {
Set-DatabasePermissions `
-ResourceGroup $RsgTarget `
-Server $SqlTarget `
-Database $DbTarget `
-Subscription $SubTarget `
-Permissions $sourcePermissions
Write-Log "Permissions migrated successfully" "SUCCESS"
}
catch {
Write-Log "Some permissions failed to migrate: $_" "WARNING"
}
# Step 5b: Set SQL user password from Key Vault if specified
if (-not [string]::IsNullOrWhiteSpace($KeyVaultName) -and -not [string]::IsNullOrWhiteSpace($SqlLoginName)) {
Write-Log "Updating password for SQL user '$SqlLoginName' from Key Vault..." "INFO"
try {
$kvSecretParams = @{
VaultName = $KeyVaultName
SecretName = $KeyVaultSecretName
}
if (-not [string]::IsNullOrWhiteSpace($KeyVaultSubscription)) {
$kvSecretParams.Subscription = $KeyVaultSubscription
}
$sqlPassword = Get-KeyVaultSecret @kvSecretParams
$passwordSet = Set-SqlUserPassword `
-Server $SqlTarget `
-Database $DbTarget `
-LoginName $SqlLoginName `
-Password $sqlPassword
if ($passwordSet) {
Write-Log "SQL user password updated successfully" "SUCCESS"
} else {
Write-Log "Failed to set SQL user password" "WARNING"
}
}
catch {
Write-Log "Failed to update SQL user password: $_" "WARNING"
}
}
}
# Step 6: Summary
Write-Log "==========================================" "SUCCESS"
Write-Log "Migration completed successfully!" "SUCCESS"
Write-Log "==========================================" "SUCCESS"
Write-Log "Target Database: $SqlTarget/$DbTarget" "INFO"
if (Test-DatabaseExists -ResourceGroup $RsgTarget -Server $SqlTarget -Database $oldDbName -Subscription $SubTarget) {
Write-Log "Previous Database: $SqlTarget/$oldDbName (kept as backup)" "INFO"
Write-Log "Remember to delete '$oldDbName' once you confirm the new database is working correctly" "INFO"
}
Write-Log "You can now update connection strings to point to: $SqlTarget/$DbTarget" "INFO"
# Switch back to source subscription
az account set --subscription $SubSource
Write-Log "Script completed successfully!" "SUCCESS"
}
catch {
Write-Log "Script failed with error: $_" "ERROR"
Write-Log $_.ScriptStackTrace "ERROR"
# Try to switch back to source subscription
try {
az account set --subscription $SubSource
}
catch {
# Ignore errors when switching back
}
exit 1
}
#endregion