forked from SQLauto/sqlmigration
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Start-SqlServerMigration.ps1
2128 lines (1731 loc) · 81.1 KB
/
Start-SqlServerMigration.ps1
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
Migrates SQL Server databases, logins, SQL Agent objects, and global configuration settings from one SQL Server to another.
.DESCRIPTION
This script provides the ability to migrate databases using detach/copy/attach or backup/restore. SQL Server logins, including passwords, SID and database/server roles can also be migrated. In addition, job server objects can be migrated and server configuration settings can be exported or migrated. This script works with named instances, clusters and SQL Express.
By default, databases will be migrated to the destination SQL Server's default data and log directories. You can override this by specifying -ReuseFolderStructure. Filestreams and filegroups are also migrated. Safety is emphasized.
THIS CODE IS PROVIDED "AS IS", WITH NO WARRANTIES.
.PARAMETER Source
Source SQL Server. You must have sysadmin access and server version must be > SQL Server 7.
.PARAMETER Destination
Destination SQL Server. You must have sysadmin access and server version must be > SQL Server 7.
.PARAMETER UseSqlLoginSource
Uses SQL Login credentials to connect to Source server. Note this is a switch. You will be prompted to enter your SQL login credentials.
Windows Authentication will be used if UseSqlLoginSource is not specified.
NOTE: Auto-populating parameters (ExcludeDBs, ExcludeLogins, IncludeDBs, IncludeLogins) are populated by the account running the PowerShell script.
.PARAMETER UseSqlLoginDestination
Uses SQL Login credentials to connect to Destination server. Note this is a switch. You will be prompted to enter your SQL login credentials.
Windows Authentication will be used if UseSqlLoginDestination is not specified. To connect as a different Windows user, run PowerShell as that user.
.PARAMETER AllUserDBs
Migrates user databases. Does not migrate system or support databases. A logfile named $SOURCE-$DESTINATION-$date-logins.csv will be written to the current directory. Requires -BackupRestore or -DetachAttach. Talk about database structure.
.PARAMETER IncludeSupportDBs
Migration of ReportServer, ReportServerTempDB, SSIDB, and distribution databases if they exist. A logfile named $SOURCE-$DESTINATION-$date-SQLs.csv will be written to the current directory. Requires -BackupRestore or -DetachAttach.
.PARAMETER BackupRestore
Use the a Copy-Only Backup and Restore Method. This parameter requires that you specify -NetworkShare in a valid UNC format (\\server\share)
.PARAMETER DetachAttach
Uses the detach/copy/attach method to perform database migrations. No files are deleted on the source. If the destination attachment fails, the source database will be reattached. File copies are performed over administrative shares (\\server\x$\mssql) using BITS. If a database is being mirrored, the mirror will be broken prior to migration.
.PARAMETER ReattachAtSource
Reattaches all source databases after DetachAttach migration.
.PARAMETER ReuseFolderStructure
By default, databases will be migrated to the destination SQL Server's default data and log directories. You can override this by specifying -ReuseFolderStructure. The same structure will be kept exactly, so consider this if you're migrating between different versions and use part of Microsoft's default SQL structure (MSSQL12.INSTANCE, etc)
.PARAMETER NetworkShare
Specifies the network location for the backup files. The SQL Service service accounts must read/write permission to access this location.
.PARAMETER AllLogins
Migrates all logins, along with their passwords, sids, databasae roles and server roles. Use ExcludeLogins to exclude specific users. Use -force to drop and recreate any existing users on destination. Otherwise, they will be skipped. The 'sa' user and users starting with ## will be skipped. Also updates database owners on destination.
.PARAMETER ExcludeDBs
Excludes specified databases when performing -AllUserDBs migrations. This list is auto-populated for tab completion.
.PARAMETER IncludeDBs
Migrates ONLY specified databases. This list is auto-populated for tab completion.
.PARAMETER ExcludeLogins
Excludes specified logins when performing -AllUserDBs migrations. This list is auto-populated for tab completion.
.PARAMETER IncludeLogins
Migrates ONLY specified logins. This list is auto-populated for tab completion.
.PARAMETER ExportSPconfigure
Exports all server configurations from sp_configure to SQL file named $SOURCE-$DESTINATION-$date-sp_configure.sql in the current directory.
Not compatible with SQL Server 2000.
.PARAMETER RunSPconfigure
Exports all global configuration options from source server and executes it on the destination server. Running ExportSPconfigure then evaluating the export and running it on the destination is recommended instead.
Not compatible with SQL Server 2000.
.PARAMETER MigrateJobServer
Migrates all job server objects, including proxy accounts, job schedules, shared schedules, alert system, job categories, operator categories, alert categories, alerts, target server groups, target servers, operators, and jobs. Existing objects will not be deleted, and no -force option is available.
.PARAMETER MigrateUserObjectsinSysDBs
This switch migrates user-created objects in the systems databases to the new server. This is useful for DBA's who create environment specific stored procedures, tables, etc in the master, model or msdb databases.
.PARAMETER SetSourceReadOnly
Sets all migrated databases to ReadOnly prior to detach/attach & backup/restore. If -ReAttachAtSource is used, db is set to read-only after reattach.
.PARAMETER Everything
Migrates all logins, databases, agent objects, except those listed by ExcludeDBs and ExcludeLogins.
Also exports sp_configure settings and user created objects within system databases.
.PARAMETER Force
If migrating users, forces drop and recreate of SQL and Windows logins.
If migrating databases, deletes existing databases with matching names.
If using -DetachAttach, -Force will break mirrors and drop dbs from Availability Groups.
MigrateJobServer not supported.
.NOTES
Author : Chrissy LeMaire
Requires: PowerShell Version 3.0, SQL Server SMO
DateUpdated: 2015-May-12
Version: 1.3.4
Limitations: Doesn't cover what it doesn't cover (replication, linked servers, certificates, etc)
SQL Server 2000 login migrations have some limitations (server perms aren't migrated, etc)
SQL Server 2000 databases cannot be directly migrated to SQL Server 2012 and above.
Logins within SQL Server 2012 and above logins cannot be migrated to SQL Server 2008 R2 and below.
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Use-PowerShell-to-Migrate-86c841df/
.EXAMPLE
.\Start-SqlServerMigration.ps1 -Source sqlserver\instance -Destination sqlcluster -DetachAttach -Everything
Description
All databases, logins, job objects and sp_configure options will be migrated from sqlserver\instance to sqlcluster. Databases will be migrated using the detach/copy files/attach method. DBowner will be updated. User passwords, SIDs, database roles and server roles will be migrated along with the login.
.EXAMPLE
.\Start-SqlServerMigration.ps1 -Source sqlserver\instance -Destination sqlcluster -AllUserDBs -ExcludeDBs Northwind, pubs -IncludeSupportDBs -force -AllLogins -ExcludeLogins nwuser, pubsuser, "corp\domain admins" -MigrateJobServer -ExportSPconfigure -UseSqlLoginSource -UseSqlLoginDestination
Description
Prompts for SQL login usernames and passwords on both the Source and Destination then connects to each using the SQL Login credentials.
All logins except for nwuser, pubsuser and the corp\domain admins group will be migrated from sqlserver\instance to sqlcluster, along with their passwords, server roles and database roles. A logfile named SQLSERVER-SQLCLUSTER-$date-logins.csv will be written to the current directory. Existing SQL users will be dropped and recreated.
Migrates all user databases except for Northwind and pubs by performing the following: kick all users out of the database, detach all data/log files, move files across the network over an admin share (\\SQLSERVER\M$\MSSQL...), attach file on destination server. If the database exists on the destination, it will be dropped prior to attach.
It also includes the support databases (ReportServer, ReportServerTempDB, SSIDB, distribution).
If the database files (*.mdf, *.ndf, *.ldf) on SQLCLUSTER exist and aren't in use, they will be overwritten. A logfile named SQLSERVER-SQLCLUSTER-$date-SQLs.csv will be written to the current directory.
All job server objects will be migrated. A logfile named SQLSERVER-SQLCLUSTER-$date-jobs.csv will be written to the current directory.
A file named SQLSERVER-SQLCluster-$date-sp_configure.sql with global server configurations will be written to the current directory. This file can then be executed manually on SQLCLUSTER.
#>
#Requires -Version 3.0
[CmdletBinding(DefaultParameterSetName="DBMigration", SupportsShouldProcess = $true)]
Param(
# Source SQL Server
[parameter(Mandatory = $true)]
[string]$Source,
# Destination SQL Server
[parameter(Mandatory = $true)]
[string]$Destination,
#Other Migrations
[switch]$AllLogins,
[switch]$MigrateJobServer,
[switch]$ExportSPconfigure,
[switch]$RunSPConfigure,
[switch]$MigrateUserObjectsinSysDBs,
# Database Migration
[Parameter(Mandatory = $true, ParameterSetName="DBAttachDetach")]
[switch]$DetachAttach,
[Parameter(Mandatory = $true,ParameterSetName="DBBackup")]
[switch]$BackupRestore,
[Parameter(ParameterSetName="DBBackup")]
[Parameter(ParameterSetName="DBAttachDetach")]
[switch]$ReuseFolderstructure,
[Parameter(ParameterSetName="DBBackup")]
[Parameter(ParameterSetName="DBAttachDetach")]
[switch]$AllUserDBs,
[Parameter(ParameterSetName="DBBackup")]
[Parameter(ParameterSetName="DBAttachDetach")]
[switch]$IncludeSupportDBs,
[Parameter(ParameterSetName="DBAttachDetach")]
[switch]$ReattachAtSource,
[Parameter(Mandatory=$true, ParameterSetName="DBBackup",
HelpMessage="Specify a valid network share in the format \\server\share that can be accessed by your account and both SQL Server service accounts.")]
[string]$NetworkShare,
[Parameter(ParameterSetName="DBBackup")]
[Parameter(ParameterSetName="DBAttachDetach")]
[switch]$Everything,
[Parameter(ParameterSetName="DBBackup")]
[Parameter(ParameterSetName="DBAttachDetach")]
[switch]$SetSourceReadOnly,
# The rest
[switch]$UseSqlLoginSource,
[switch]$UseSqlLoginDestination,
[switch]$Force
)
DynamicParam {
if ($Source) {
# Check for SMO and SQL Server access
if ([Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") -eq $null) {return}
$server = New-Object Microsoft.SqlServer.Management.Smo.Server $source
$server.ConnectionContext.ConnectTimeout = 2
try { $server.ConnectionContext.Connect() } catch { return }
$SupportDBs = "ReportServer","ReportServerTempDB", "SSISDB", "distribution"
# Populate arrays
$databaselist = @(); $loginlist = @()
foreach ($database in $server.databases) {
if ((!$database.IsSystemObject) -and $SupportDBs -notcontains $database.name) {
$databaselist += $database.name}
}
foreach ($login in $server.logins) {
if (!$login.name.StartsWith("##") -and $login.name -ne 'sa') {
$loginlist += $login.name}
}
# Reusable parameter setup
$newparams = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
$attributes = New-Object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "__AllParameterSets"
$attributes.Mandatory = $false
# Database list parameter setup
if ($databaselist) { $dbvalidationset = New-Object System.Management.Automation.ValidateSetAttribute -ArgumentList $databaselist }
$dbattributes = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$dbattributes.Add($attributes)
if ($databaselist) { $dbattributes.Add($dbvalidationset) }
$IncludeDBs = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("IncludeDBs", [String[]], $dbattributes)
$ExcludeDBs = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("ExcludeDBs", [String[]], $dbattributes)
# Login list parameter setup
if ($loginlist) { $loginvalidationset = New-Object System.Management.Automation.ValidateSetAttribute -ArgumentList $loginlist }
$loginattributes = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$loginattributes.Add($attributes)
if ($loginlist) { $loginattributes.Add($loginvalidationset) }
$IncludeLogins = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("IncludeLogins", [String[]], $loginattributes)
$ExcludeLogins = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("ExcludeLogins", [String[]], $loginattributes)
$newparams.Add("IncludeDBs", $IncludeDBs)
$newparams.Add("ExcludeDBs", $ExcludeDBs)
$newparams.Add("IncludeLogins", $IncludeLogins)
$newparams.Add("ExcludeLogins", $ExcludeLogins)
$server.ConnectionContext.Disconnect()
return $newparams
}
}
BEGIN {
# Essential Database Functions
Function Backup-SQLDatabase {
<#
.SYNOPSIS
Makes a full database backup of a database to a specified directory. $server is an SMO server object.
.EXAMPLE
Backup-SQLDatabase $smoserver $dbname \\fileserver\share\sql\database.bak
.OUTPUTS
$true if success
$false if failure
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[object]$server,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$dbname,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$backupfile
)
$server.ConnectionContext.StatementTimeout = 0
$backup = New-Object "Microsoft.SqlServer.Management.Smo.Backup"
$backup.Action = "Database"
$backup.CopyOnly = $true
$device = New-Object "Microsoft.SqlServer.Management.Smo.BackupDeviceItem"
$device.DeviceType = "File"
$device.Name = $backupfile
$backup.Devices.Add($device)
$backup.Database = $dbname
$percent = [Microsoft.SqlServer.Management.Smo.PercentCompleteEventHandler] {
Write-Progress -id 1 -activity "Backing up database $dbname to $backupfile" -percentcomplete $_.Percent -status ([System.String]::Format("Progress: {0} %", $_.Percent))
}
$backup.add_PercentComplete($percent)
$backup.add_Complete($complete)
Write-Progress -id 1 -activity "Backing up database $dbname to $backupfile" -percentcomplete 0 -status ([System.String]::Format("Progress: {0} %", 0))
Write-Host "Backing up $dbname" -ForegroundColor Yellow
try {
$backup.SqlBackup($server)
Write-Progress -id 1 -activity "Backing up database $dbname to $backupfile" -status "Complete" -Completed
Write-Host "Backup succeeded" -ForegroundColor Green
return $true
}
catch {
Write-Progress -id 1 -activity "Backup" -status "Failed" -completed
return $false
}
}
Function Restore-SQLDatabase {
<#
.SYNOPSIS
Restores .bak file to SQL database. Creates db if it doesn't exist. $filestructure is
a custom object that contains logical and physical file locations.
.EXAMPLE
$filestructure = Get-SQLFileStructures $sourceserver $destserver $ReuseFolderstructure
Restore-SQLDatabase $destserver $dbname $backupfile $filestructure
.OUTPUTS
$true if success
$true if failure
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[object]$server,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$dbname,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$backupfile,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[object]$filestructure
)
$servername = $server.name
$server.ConnectionContext.StatementTimeout = 0
$restore = New-Object "Microsoft.SqlServer.Management.Smo.Restore"
foreach ($file in $filestructure.databases[$dbname].destination.values) {
$movefile = New-Object "Microsoft.SqlServer.Management.Smo.RelocateFile"
$movefile.LogicalFileName = $file.logical
$movefile.PhysicalFileName = $file.physical
$null = $restore.RelocateFiles.Add($movefile)
}
Write-Host "Restoring $dbname to $servername" -ForegroundColor Yellow
try {
$percent = [Microsoft.SqlServer.Management.Smo.PercentCompleteEventHandler] {
Write-Progress -id 1 -activity "Restoring $dbname to $servername" -percentcomplete $_.Percent -status ([System.String]::Format("Progress: {0} %", $_.Percent))
}
$restore.add_PercentComplete($percent)
$restore.PercentCompleteNotification = 1
$restore.add_Complete($complete)
$restore.ReplaceDatabase = $true
$restore.Database = $dbname
$restore.Action = "Database"
$restore.NoRecovery = $false
$device = New-Object -TypeName Microsoft.SqlServer.Management.Smo.BackupDeviceItem
$device.name = $backupfile
$device.devicetype = "File"
$restore.Devices.Add($device)
Write-Progress -id 1 -activity "Restoring $dbname to $servername" -percentcomplete 0 -status ([System.String]::Format("Progress: {0} %", 0))
$restore.sqlrestore($server)
Write-Progress -id 1 -activity "Restoring $dbname to $servername" -status "Complete" -Completed
return $true
} catch {
write-warning "Restore failed: $($_.Exception.InnerException.Message)"
return $false
}
}
Function Get-SQLFileStructures {
<#
.SYNOPSIS
Custom object that contains file structures and remote paths (\\sqlserver\m$\mssql\etc\etc\file.mdf) for
source and destination servers.
.EXAMPLE
$filestructure = Get-SQLFileStructures $sourceserver $destserver $ReuseFolderstructure
foreach ($file in $filestructure.databases[$dbname].destination.values) {
Write-Host $file.physical
Write-Host $file.logical
Write-Host $file.remotepath
}
.OUTPUTS
Custom object
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true,Position=0)]
[ValidateNotNullOrEmpty()]
[object]$sourceserver,
[Parameter(Mandatory = $true,Position=1)]
[ValidateNotNullOrEmpty()]
[object]$destserver,
[Parameter(Mandatory = $false,Position=2)]
[bool]$ReuseFolderstructure
)
$sourcenetbios = Get-NetBIOSName $sourceserver
$destnetbios = Get-NetBIOSName $destserver
$dbcollection = @{};
foreach ($db in $sourceserver.databases) {
$dbstatus = $db.status.toString()
if ($dbstatus.StartsWith("Normal") -eq $false) { continue }
$destinationfiles = @{}; $sourcefiles = @{}
# Data Files
foreach ($filegroup in $db.filegroups) {
foreach ($file in $filegroup.files) {
# Destination File Structure
$d = @{}
if ($ReuseFolderstructure) {
$d.physical = $file.filename
} else {
$directory = Get-SQLDefaultPaths $destserver data
$filename = Split-Path $($file.filename) -leaf
$d.physical = "$directory\$filename"
}
$d.logical = $file.name
$d.remotefilename = Join-AdminUNC $destnetbios $d.physical
$destinationfiles.add($file.name,$d)
# Source File Structure
$s = @{}
$s.logical = $file.name
$s.physical = $file.filename
$s.remotefilename = Join-AdminUNC $sourcenetbios $s.physical
$sourcefiles.add($file.name,$s)
}
}
# Add support for Full Text Catalogs in SQL Server 2005 and below
if ($sourceserver.VersionMajor -lt 10) {
foreach ($ftc in $db.FullTextCatalogs) {
# Destination File Structure
$d = @{}
$pre = "sysft_"
$name = $ftc.name
$physical = $ftc.RootPath
$logical = "$pre$name"
if ($ReuseFolderstructure) {
$d.physical = $physical
} else {
$directory = Get-SQLDefaultPaths $destserver data
if ($destserver.VersionMajor -lt 10) { $directory = "$directory\FTDATA" }
$filename = Split-Path($physical) -leaf
$d.physical = "$directory\$filename"
}
$d.logical = $logical
$d.remotefilename = Join-AdminUNC $destnetbios $d.physical
$destinationfiles.add($logical,$d)
# Source File Structure
$s = @{}
$pre = "sysft_"
$name = $ftc.name
$physical = $ftc.RootPath
$logical = "$pre$name"
$s.logical = $logical
$s.physical = $physical
$s.remotefilename = Join-AdminUNC $sourcenetbios $s.physical
$sourcefiles.add($logical,$s)
}
}
# Log Files
foreach ($file in $db.logfiles) {
$d = @{}
if ($ReuseFolderstructure) {
$d.physical = $file.filename
} else {
$directory = Get-SQLDefaultPaths $destserver log
$filename = Split-Path $($file.filename) -leaf
$d.physical = "$directory\$filename"
}
$d.logical = $file.name
$d.remotefilename = Join-AdminUNC $destnetbios $d.physical
$destinationfiles.add($file.name,$d)
$s = @{}
$s.logical = $file.name
$s.physical = $file.filename
$s.remotefilename = Join-AdminUNC $sourcenetbios $s.physical
$sourcefiles.add($file.name,$s)
}
$location = @{}
$location.add("Destination",$destinationfiles)
$location.add("Source",$sourcefiles)
$dbcollection.Add($($db.name),$location)
}
$filestructure = [pscustomobject]@{"databases" = $dbcollection}
return $filestructure
}
Function Dismount-SQLDatabase {
<#
.SYNOPSIS
Detaches a SQL Server database. $server is an SMO server object.
.EXAMPLE
$detachresult = Dismount-SQLDatabase $server $dbname
.OUTPUTS
$true if success
$false if failure
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[object]$server,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$dbname
)
$database = $server.databases[$dbname]
if ($database.IsMirroringEnabled) {
try {
Write-Warning "Breaking mirror for $dbname"
$database.ChangeMirroringState([Microsoft.SqlServer.Management.Smo.MirroringOption]::Off)
$database.Alter()
$database.Refresh()
Write-Warning "Could not break mirror for $dbname. Skipping."
} catch { return $false }
}
if ($database.AvailabilityGroupName.Length -gt 0 ) {
$agname = $database.AvailabilityGroupName
Write-Host "Attempting remove from Availability Group $agname" -ForegroundColor Yellow
try {
$server.AvailabilityGroups[$database.AvailabilityGroupName].AvailabilityDatabases[$dbname].Drop()
Write-Host "Successfully removed $dbname from detach from $agname on $($server.name)" -ForegroundColor Green
} catch { Write-Host "Could not remove $dbname from $agname on $($server.name)" -ForegroundColor Red; return $false }
}
Write-Host "Attempting detach from $dbname from $source" -ForegroundColor Yellow
####### Using SQL to detach does not modify the $database collection #######
$sql = "ALTER DATABASE [$dbname] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;EXEC master.dbo.sp_detach_db N'$dbname'"
try {
$null = $server.ConnectionContext.ExecuteNonQuery($sql)
Write-Host "Successfully detached $dbname from $source" -ForegroundColor Green
return $true
}
catch { return $false }
}
Function Mount-SQLDatabase {
<#
SYNOPSIS
Attaches a SQL Server database, and sets its owner. $server is an SMO server object.
.EXAMPLE
Mount-SQLDatabase $destserver $dbname $destfilestructure $dbowner
.OUTPUTS
$true if success
$false if failure
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[object]$server,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$dbname,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[object]$filestructure,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$dbowner
)
if ($server.Logins.Item($dbowner) -eq $null) { $dbowner = 'sa' }
try {
$null = $server.AttachDatabase($dbname, $filestructure, $dbowner, [Microsoft.SqlServer.Management.Smo.AttachOptions]::None)
return $true
} catch { return $false }
}
Function Start-SQLBackupRestore {
<#
.SYNOPSIS
Performs checks, then executes Backup-SQLDatabase to a fileshare and then a subsequential Restore-SQLDatabase.
.EXAMPLE
Start-SQLBackupRestore $sourceserver $destserver $dbname $networkshare $force
.OUTPUTS
$true if successful
error string if failure
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[object]$sourceserver,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[object]$destserver,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$dbname,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[ValidateScript({ Test-Path $_ })]
[string]$networkshare,
[Parameter()]
[bool]$force
)
$filestructure = Get-SQLFileStructures $sourceserver $destserver $ReuseFolderstructure
$filename = "$dbname-$timenow.bak"
$backupfile = Join-Path $networkshare $filename
$backupresult = Backup-SQLDatabase $sourceserver $dbname $backupfile
if ($backupresult) {
$restoreresult = Restore-SQLDatabase $destserver $dbname $backupfile $filestructure
if ($restoreresult) {
# RESTORE was successful
Write-Host "Successfully restored $dbname to $destination" -ForegroundColor Green
return $true
} else {
# RESTORE was unsuccessful
if ($ReuseFolderStructure) {
Write-Host "Failed to restore $dbname to $destination. You specified -ReuseFolderStructure. Does the exact same destination directory structure exist?" -ForegroundColor Red
return "Failed to restore $dbname to $destination using ReuseFolderStructure."
}
else {
Write-Host "Failed to restore $dbname to $destination" -ForegroundColor Red
return "Failed to restore $dbname to $destination."
}
}
} else {
# add to failed because BACKUP was unsuccessful
Write-Host "Backup Failed. Does SQL Server account ($($sourceserver.ServiceAccount)) have access to $($NetworkShare)?" -ForegroundColor Red
return "Backup Failed. Does SQL Server account ($($sourceserver.ServiceAccount)) have access to $NetworkShare?"
}
}
Function Start-SQLDetachAttach {
<#
.SYNOPSIS
Performs checks, then executes Dismount-SQLDatabase on a database, copies its files to the new server,
then performs Mount-SQLDatabase. $sourceserver and $destserver are SMO server objects.
$filestructure is a custom object generated by Get-SQLFileStructures
.EXAMPLE
result = Start-SQLDetachAttach $sourceserver $destserver $filestructure $dbname $force
.OUTPUTS
$true if successful
error string if failure
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[object]$sourceserver,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[object]$destserver,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[object]$filestructure,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$dbname,
[Parameter()]
[bool]$force
)
$destfilestructure = New-Object System.Collections.Specialized.StringCollection
$sourcefilestructure = New-Object System.Collections.Specialized.StringCollection
$dbowner = $sourceserver.databases[$dbname].owner; if ($dbowner -eq $null) { $dbowner = 'sa' }
foreach ($file in $filestructure.databases[$dbname].destination.values) {$null = $destfilestructure.add($file.physical) }
foreach ($file in $filestructure.databases[$dbname].source.values) {$null = $sourcefilestructure.add($file.physical) }
$detachresult = Dismount-SQLDatabase $sourceserver $dbname
if ($detachresult) {
$transfer = Start-SQLFileTransfer $filestructure $dbname
if ($transfer -eq $false) { Write-Warning "Could not copy files."; return "Could not copy files." }
$attachresult = Mount-SQLDatabase $destserver $dbname $destfilestructure $dbowner
if ($attachresult -eq $true) {
# add to added dbs because ATTACH was successful
Write-Host "Successfully attached $dbname to $destination" -ForegroundColor Green
return $true
} else {
# add to failed because ATTACH was unsuccessful
Write-Warning "Could not attach $dbname."
return "Could not attach database."
}
}
else {
# add to failed because DETACH was unsuccessful
Write-Warning "Could not detach $dbname."
return "Could not detach database."
}
}
Function Copy-SqlDatabases {
<#
.SYNOPSIS
Performs tons of checks then migrates the databases.
.EXAMPLE
Copy-SqlDatabases $sourceserver $destserver $AllUserDBs $IncludeDBs $ExcludeDBs $IncludeSupportDBs $force
.OUTPUTS
CSV files and informational messages.
#>
[cmdletbinding(SupportsShouldProcess = $true)]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[object]$sourceserver,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[object]$destserver,
[Parameter()]
[bool]$AllUserDBs,
[Parameter()]
[string[]]$IncludeDBs,
[Parameter()]
[string[]]$ExcludeDBs,
[Parameter()]
[string]
$IncludeSupportDBs,
[Parameter()]
[bool]$force
)
<# ###############################################################
Server Checks
############################################################### #>
$alldbelapsed = [System.Diagnostics.Stopwatch]::StartNew()
if ($sourceserver.Databases.count -le 4) { throw "No user databases to migrate. Quitting." }
if ([version]$sourceserver.ResourceVersionString -gt [version]$destserver.ResourceVersionString) {
throw "Source SQL Server version build must be <= destination SQL Server for database migration."
}
if ($fswarning) { Write-Warning "FILESTREAM enabled on $source but not $destination. Databases that use FILESTREAM will be skipped." }
Write-Host "Checking access to remote directories..." -ForegroundColor Yellow
$sourcenetbios = Get-NetBIOSName $sourceserver
$destnetbios = Get-NetBIOSName $destserver
If (!(Test-Path (Join-AdminUNC $sourcenetbios (Get-SQLDefaultPaths $sourceserver data)))) {
Write-Host "Can't access remote SQL directories on $source. Halting database migration." -ForegroundColor Red
return
}
If (!(Test-Path (Join-AdminUNC $destnetbios (Get-SQLDefaultPaths $destserver data)))) {
Write-Host "Can't access remote SQL directories on $destination. Halting database migration." -ForegroundColor Red
return
}
##################################################################
$SupportDBs = "ReportServer","ReportServerTempDB", "SSISDB", "distribution"
$sa = $changedbowner
$timenow = (Get-Date -uformat "%m%d%Y%H%M%S")
$csvfilename = "$($sourceserver.name.replace('\','$'))-to-$($destserver.name.replace('\','$'))-$timenow"
$migrateddb = @{}; $skippedb = @{}
$ExcludeDBs | Where-Object {!([string]::IsNullOrEmpty($_))} | ForEach-Object { $skippedb.Add($_,"Explicitly Skipped") }
$filestructure = Get-SQLFileStructures $sourceserver $destserver $ReuseFolderstructure
Set-Content -Path "$csvfilename-db.csv" "Database Name, Result, Start, Finish"
foreach ($database in $sourceserver.databases) {
$dbelapsed = [System.Diagnostics.Stopwatch]::StartNew()
$dbname = $database.name
$dbowner = $database.Owner
<# ###############################################################
Database Checks
############################################################### #>
if ($database.id -le 4) { continue }
if ($IncludeDBs -and $IncludeDBs -notcontains $dbname) { continue }
if ($IncludeSupportDBs -eq $false -and $SupportDBs -contains $dbname) { continue }
Write-Host "`n######### Database: $dbname #########" -ForegroundColor White
$dbstart = Get-Date
if ($skippedb.ContainsKey($dbname) -and $IncludeDBs -eq $null) {
Write-Host "`nSkipping $dbname" -ForegroundColor Cyan
continue
}
if (($database.status.toString()).StartsWith("Normal") -eq $false) {
Write-Warning "Skipping $dbname. Status not Normal."
$skippedb.Add($dbname,"Skipped. Database status not Normal (Status: $($database.status)).")
continue
}
if ($fswarning -and ($database.FileGroups | Where { $_.isFilestream }) -ne $null) {
Write-Warning "Skipping $dbname (contains FILESTREAM)"
$skippedb.Add($dbname,"Skipped. Database contains FILESTREAM and FILESTREAM is disabled on $destination.")
continue
}
if ($ReuseFolderstructure) {
$remotepath = Split-Path ($database.FileGroups[0].Files.FileName)
$remotepath = Join-AdminUNC $destnetbios $remotepath
if (!(Test-Path $remotepath)) { throw "Cannot resolve $remotepath. `n`nYou have specified ReuseFolderstructure and exact folder structure does not exist. Halting script." }
}
if ($database.AvailabilityGroupName.Length -gt 0 -and !$force -and $DetachAttach) {
$agname = $database.AvailabilityGroupName
Write-Warning "Database is part of an Availability Group ($agname). Use -Force to drop from $agname and migrate. Alternatively, you can use the safer backup/restore method."
$skippedb[$dbname] = "Database is part of an Availability Group ($agname) and -force was not specified. Skipped."
continue
}
if ($database.IsMirroringEnabled -and !$force -and $DetachAttach) {
Write-Warning "Database is being mirrored. Use -Force to break mirror and migrate. Alternatively, you can use the safer backup/restore method."
$skippedb[$dbname] = "Database is being mirrored and -force was not specified. Skipped."
continue
}
if ($destserver.Databases[$dbname] -ne $null -and !$force) {
Write-Warning "Database exists at destination. Use -Force to drop and migrate."
$skippedb[$dbname] = "Database exists at destination. Use -Force to drop and migrate."
continue
}
elseif ($destserver.Databases[$dbname] -ne $null -and $force) {
If ($Pscmdlet.ShouldProcess($destination,"DROP DATABASE $dbname")) {
Write-Host "$dbname already exists. -Force was specified. Dropping $dbname on $destination." -ForegroundColor Yellow
$dropresult = Drop-SQLDatabase $destserver $dbname
if (!$dropresult) { $skippedb[$dbname] = "Database exists and could not be dropped."; continue }
}
}
If ($Pscmdlet.ShouldProcess("local host","Showing start time")) {
Write-Host "Started: $dbstart" -ForegroundColor Cyan
}
if ($sourceserver.versionMajor -ge 9) {
$sourcedbownerchaining = $sourceserver.databases[$dbname].DatabaseOwnershipChaining
$sourcedbtrustworthy = $sourceserver.databases[$dbname].Trustworthy
$sourcedbbrokerenabled = $sourceserver.databases[$dbname].BrokerEnabled
}
$sourcedbreadonly = $sourceserver.Databases[$dbname].ReadOnly
if ($SetSourceReadOnly) {
If ($Pscmdlet.ShouldProcess($source,"Set $dbname to read-only")) {
$result = Update-SQLdbReadOnly $sourceserver $dbname $true
}
}
if ($BackupRestore) {
If ($Pscmdlet.ShouldProcess($destination,"Backup $dbname from $source and restoring.")) {
$result = (Start-SQLBackupRestore $sourceserver $destserver $dbname $networkshare $force)
$dbfinish = Get-Date
if ($result -eq $true) {
$migrateddb.Add($dbname,"Successfully migrated,$dbstart,$dbfinish")
Add-Content -Path "$csvfilename-db.csv" "$dbname,Successfully migrated,$dbstart,$dbfinish"
$result = Update-SQLdbowner $sourceserver $destserver -dbname $dbname
If ($result) {
Add-Content -Path "$csvfilename-dbowner.csv" "$dbname,$dbowner"
}
} else {
$skippedb[$dbname] = $result
Add-Content -Path "$csvfilename-db.csv" "$dbname,Migration failed - $result,$dbstart,$dbfinish"
}
}
} # End of backup
elseif ($DetachAttach) {
$sourcefilestructure = New-Object System.Collections.Specialized.StringCollection
foreach ($file in $filestructure.databases[$dbname].source.values) {$null = $sourcefilestructure.add($file.physical) }
$dbowner = $sourceserver.databases[$dbname].owner; if ($dbowner -eq $null) { $dbowner = "sa" }
If ($Pscmdlet.ShouldProcess($destination,"Detach $dbname from $source and attach, then update dbowner")) {
$result = Start-SQLDetachAttach $sourceserver $destserver $filestructure $dbname $force
$dbfinish = Get-Date
if ($result -eq $true) {
$migrateddb.Add($dbname,"Successfully migrated,$dbstart,$dbfinish")
Add-Content -Path "$csvfilename-db.csv" "$dbname,Successfully migrated,$dbstart,$dbfinish"
$result = Update-SQLdbowner $sourceserver $destserver -dbname $dbname
If ($result) {
Add-Content -Path "$csvfilename-dbowner.csv" "$dbname,$dbowner"
}
} else {
$skippedb[$dbname] = $result
Add-Content -Path "$csvfilename-db.csv" "$dbname,Migration failed - $result,$dbstart,$dbfinish"
}
if ($ReattachAtSource) {
$null = ($sourceserver.databases).Refresh()
$result = Mount-SQLDatabase $sourceserver $dbname $sourcefilestructure $dbowner
if ($result -eq $true) {
$sourceserver.databases[$dbname].DatabaseOwnershipChaining = $sourcedbownerchaining
$sourceserver.databases[$dbname].Trustworthy = $sourcedbtrustworthy
$sourceserver.databases[$dbname].BrokerEnabled = $sourcedbbrokerenabled
$sourceserver.databases[$dbname].alter()
if ($SetSourceReadOnly) {
$null = Update-SQLdbReadOnly $sourceserver $dbname $true
} else { $null = Update-SQLdbReadOnly $sourceserver $dbname $sourcedbreadonly }
Write-Host "Successfully reattached $dbname to $source" -ForegroundColor Green
}
else { Write-Warning "Could not reattach $dbname to $source." }
}
}
} #end of if detach/backup
# restore poentially lost settings
if ($destserver.versionMajor -ge 9) {
if ($sourcedbownerchaining -ne $destserver.databases[$dbname].DatabaseOwnershipChaining ) {
If ($Pscmdlet.ShouldProcess($destination,"Updating DatabaseOwnershipChaining on $dbname")) {
try {
$destserver.databases[$dbname].DatabaseOwnershipChaining = $sourcedbownerchaining
$destserver.databases[$dbname].alter()
Write-Host "Successfully updated DatabaseOwnershipChaining for $sourcedbownerchaining on $dbname on $destination" -ForegroundColor Green
} catch { Write-Host "Failed to update DatabaseOwnershipChaining for $sourcedbownerchaining on $dbname on $destination" -ForegroundColor Red }
}
}
if ($sourcedbtrustworthy -ne $destserver.databases[$dbname].Trustworthy ) {
If ($Pscmdlet.ShouldProcess($destination,"Updating Trustworthy on $dbname")) {
try {
$destserver.databases[$dbname].Trustworthy = $sourcedbtrustworthy
$destserver.databases[$dbname].alter()