Repository navigation
Expand file tree
/
Copy path30_DataBase_Objects.ps1
More file actions
775 lines (647 loc) · 26.5 KB
/
Copy path30_DataBase_Objects.ps1
File metadata and controls
775 lines (647 loc) · 26.5 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
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
<#
.SYNOPSIS
Gets the core Database Objects on the target server
.DESCRIPTION
Writes the Objects out into subfolders in the "30 - DataBase Objects" folder
Scripted Objects include:
Database definition with Files and Filegroups
DataBase Triggers
Filegroups
Full Text Catalogs
Schemas
Sequences
Stored Procedures
Synonyms
Tables
Table Triggers
User Defined Functions
User Defined Table Types
Views
.EXAMPLE
30_DataBase_Objects.ps1 localhost
.EXAMPLE
30_DataBase_Objects.ps1 server01 sa password
.EXAMPLE
30_Database_Objects.ps1 -SQLInstance localhost -myuser username -mypass password -myDatabase AdventureWorks2014 -myTable Person.Address
.Inputs
ServerName, [SQLUser], [SQLPassword], [myDatabase]
.Outputs
.NOTES
Use the -myDatabase parameter to just script out one database
Use the -myTable parameter to just script out one table in the above Database
.LINK
https://github.com/gwalkey
#>
[CmdletBinding()]
Param(
[string]$SQLInstance = "localhost",
[string]$myuser,
[string]$mypass,
[string]$myDatabase,
[string]$mytable
)
# Load Common Modules and .NET Assemblies
try
{
Import-Module ".\SQLTranscriptase.psm1" -ErrorAction Stop
}
catch
{
Throw('SQLTranscriptase.psm1 not found')
}
LoadSQLSMO
# Init
Set-StrictMode -Version latest;
[string]$BaseFolder = (Get-Item -Path ".\" -Verbose).FullName
Write-Host -f Yellow -b Black "30 - DataBase Objects"
Write-Output("Server: [{0}]" -f $SQLInstance)
# Parameter check: Table needs matching Database parameter
if ($myTable.Length -gt 0 -and $myDatabase.Length -eq 0)
{
Write-Output ("Please specify the -MyDatabase parameter when using -myTable with {0}" -f $mytable)
exit
}
# Server connection check
$SQLCMD1 = "select serverproperty('productversion') as 'Version'"
try
{
if ($mypass.Length -ge 1 -and $myuser.Length -ge 1)
{
Write-Output "Testing SQL Auth"
$myver = ConnectSQLAuth -SQLInstance $SQLInstance -Database "master" -SQLExec $SQLCMD1 -User $myuser -Password $mypass -ErrorAction Stop| select -ExpandProperty Version
$serverauth="sql"
}
else
{
Write-Output "Testing Windows Auth"
$myver = ConnectWinAuth -SQLInstance $SQLInstance -Database "master" -SQLExec $SQLCMD1 -ErrorAction Stop | select -ExpandProperty Version
$serverauth = "win"
}
if($myver -ne $null)
{
Write-Output ("SQL Version: {0}" -f $myver)
}
}
catch
{
Write-Host -f red "$SQLInstance appears offline."
Set-Location $BaseFolder
exit
}
[int]$ver = GetSQLNumericalVersion $myver
function CopyObjectsToFiles($objects, $outDir) {
if (-not (Test-Path $outDir)) {
[System.IO.Directory]::CreateDirectory($outDir) | out-null
}
foreach ($o in $objects) {
if ($o -ne $null) {
$schemaPrefix = ""
try
{
if ($o.Schema -ne $null -and $o.Schema -ne "")
{
$schemaPrefix = $o.Schema + "."
}
}
catch
{
}
$fixedOName = $o.name.replace('\','_')
$scripter.Options.FileName = $outDir + $schemaPrefix + $fixedOName + ".sql"
try
{
$urn = new-object Microsoft.SQlserver.Management.sdk.sfc.urn($o.Urn);
$scripter.Script($urn)
}
catch
{
$msg = "Cannot script this element:"+$o
Write-Output $msg
}
}
}
}
# New UP SQL SMO Object
if ($serverauth -eq "win")
{
$srv = New-Object "Microsoft.SqlServer.Management.SMO.Server" $SQLInstance
$scripter = New-Object ("Microsoft.SqlServer.Management.SMO.Scripter") ($SQLInstance)
}
else
{
$srv = New-Object "Microsoft.SqlServer.Management.SMO.Server" $SQLInstance
$srv.ConnectionContext.LoginSecure=$false
$srv.ConnectionContext.set_Login($myuser)
$srv.ConnectionContext.set_Password($mypass)
$scripter = New-Object ("Microsoft.SqlServer.Management.SMO.Scripter") ($srv)
}
# Find/Inspect other Server-Level Objects here
Write-Output "Looking for Objects..."
# HTML CSS
$head = "<style type='text/css'>"
$head+="
table
{
Margin: 0px 0px 0px 4px;
Border: 1px solid rgb(190, 190, 190);
Font-Family: Tahoma;
Font-Size: 9pt;
Background-Color: rgb(252, 252, 252);
}
tr:hover td
{
Background-Color: rgb(150, 150, 220);
Color: rgb(255, 255, 255);
}
tr:nth-child(even)
{
Background-Color: rgb(242, 242, 242);
}
th
{
Text-Align: Left;
Color: rgb(150, 150, 220);
Padding: 1px 4px 1px 4px;
}
td
{
Vertical-Align: Top;
Padding: 1px 4px 1px 4px;
}
"
$head+="</style>"
$RunTime = Get-date
# Create Database Summary Listing
$sqlCMD2 =
"
SELECT
DB_NAME(m.[database_id]) AS [Database_Name],
m.[file_id],
m.name as 'Name',
m.physical_name as 'FileName',
m.type_desc as 'Type',
m.state_desc as 'State',
case when m.is_percent_growth=1 then '%' else 'MB' end as 'Growth',
case when m.is_percent_growth=1 then growth else CONVERT(float, m.growth/128.0) end AS [Growth_in_MB],
CONVERT(float, m.size/128.0) AS [DB_Size_in_MB],
D.collation_name,
D.compatibility_level
FROM sys.master_files M WITH (NOLOCK)
inner join sys.databases D
ON M.database_id = D.database_id
ORDER BY DB_NAME(m.[database_id]) OPTION (RECOMPILE);
"
if ($serverauth -eq "win")
{
$sqlresults1 = ConnectWinAuth -SQLInstance $SQLInstance -Database "master" -SQLExec $sqlCMD2
}
else
{
$sqlresults1 = ConnectSQLAuth -SQLInstance $SQLInstance -Database "master" -SQLExec $sqlCMD2 -User $myuser -Password $mypass
}
$RunTime = Get-date
$FullFolderPath = "$BaseFolder\$SQLInstance\30 - DataBase Objects\"
if(!(test-path -path $FullFolderPath))
{
mkdir $FullFolderPath | Out-Null
}
$myoutputfile4 = $FullFolderPath+"\Database_Summary.html"
$myHtml1 = $sqlresults1 | select Database_Name,file_id, Name, FileName, Type, State, growth, growth_in_mb, DB_Size_in_MB | ConvertTo-Html -Fragment -as table -PreContent "<h1>Server: $SqlInstance</H1><H2>Database Summary</h2>"
Convertto-Html -head $head -Body "$myHtml1" -Title "Database Summary" -PostContent "<h3>Ran on : $RunTime</h3>" | Set-Content -Path $myoutputfile4
# Create Database Object Reconstruction Order Hints File
"Database Object Reconstruction Order" | out-file "$FullFolderPath\Database_Reconstruction_Hints.txt" -Encoding ascii -Append
"`n " | out-file "$FullFolderPath\Database_Reconstruction_Hints.txt" -Encoding ascii -Append
"01) Database itself with Filegroups and Files" | out-file "$FullFolderPath\Database_Reconstruction_Hints.txt" -Encoding ascii -Append
"02) .NET Assemblies" | out-file "$FullFolderPath\Database_Reconstruction_Hints.txt" -Encoding ascii -Append
"03) Linked Servers" | out-file "$FullFolderPath\Database_Reconstruction_Hints.txt" -Encoding ascii -Append
"04) Logins" | out-file "$FullFolderPath\Database_Reconstruction_Hints.txt" -Encoding ascii -Append
"05) Sequences" | out-file "$FullFolderPath\Database_Reconstruction_Hints.txt" -Encoding ascii -Append
"06) Synonyms" | out-file "$FullFolderPath\Database_Reconstruction_Hints.txt" -Encoding ascii -Append
"07) Schemas" | out-file "$FullFolderPath\Database_Reconstruction_Hints.txt" -Encoding ascii -Append
"08) UDFs (Table-Valued and Scalar Functions)" | out-file "$FullFolderPath\Database_Reconstruction_Hints.txt" -Encoding ascii -Append
"09) User-Defined Table Types" | out-file "$FullFolderPath\Database_Reconstruction_Hints.txt" -Encoding ascii -Append
"10) Tables (with DRI Dependencies)" | out-file "$FullFolderPath\Database_Reconstruction_Hints.txt" -Encoding ascii -Append
"11) Views" | out-file "$FullFolderPath\Database_Reconstruction_Hints.txt" -Encoding ascii -Append
"12) Stored Procedures" | out-file "$FullFolderPath\Database_Reconstruction_Hints.txt" -Encoding ascii -Append
"13) Full-Text Catalogs" | out-file "$FullFolderPath\Database_Reconstruction_Hints.txt" -Encoding ascii -Append
"14) Table Triggers" | out-file "$FullFolderPath\Database_Reconstruction_Hints.txt" -Encoding ascii -Append
"15) Database Triggers" | out-file "$FullFolderPath\Database_Reconstruction_Hints.txt" -Encoding ascii -Append
# Add your favorite options from
# https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.scriptingoptions.aspx
# https://www.simple-talk.com/sql/database-administration/automated-script-generation-with-powershell-and-smo/
$scripter.Options.AllowSystemObjects = $false
$scripter.Options.AnsiFile = $true
$scripter.Options.ClusteredIndexes = $true
$scripter.Options.DriAllKeys = $true
$scripter.Options.DriForeignKeys = $true
$scripter.Options.DriChecks = $true
$scripter.Options.DriPrimaryKey = $true
$scripter.Options.DriUniqueKeys = $true
$scripter.Options.DriWithNoCheck = $true
$scripter.Options.DriAllConstraints = $true
$scripter.Options.DriIndexes = $true
$scripter.Options.DriClustered = $true
$scripter.Options.DriNonClustered = $true
$scripter.Options.EnforceScriptingOptions = $true
$scripter.Options.ExtendedProperties = $true
$scripter.Options.FullTextCatalogs = $true
$scripter.Options.FullTextIndexes = $true
$scripter.Options.FullTextStopLists = $true
$scripter.Options.IncludeFullTextCatalogRootPath= $true
$scripter.Options.IncludeHeaders = $true
$scripter.Options.IncludeDatabaseRoleMemberships= $true
$scripter.Options.IncludeDatabaseContext = $true;
$scripter.Options.Indexes = $true;
# https://connect.microsoft.com/SQLServer/feedback/details/790757/microsoft-sqlserver-management-smo-trasnfer-does-not-honor-scriptingoptions-nofilegroup-for-schema-transfer
# Closed as wont fix??
#$scripter.Options.NoFileGroup = $false;
$scripter.Options.NoCommandTerminator = $false;
$scripter.Options.NonClusteredIndexes = $true
$scripter.Options.NoTablePartitioningSchemes = $false
$scripter.Options.Permissions = $true
$scripter.Options.SchemaQualify = $true
$scripter.Options.SchemaQualifyForeignKeysReferences = $true
$scripter.Options.ToFileOnly = $true
$scripter.Options.Triggers = $true
# WithDependencies creates one huge file for all tables in the order needed to maintain Referential Integrity - but REALLY HARD TO READ
$scripter.Options.WithDependencies = $false # Leave OFF - creates issues - Jan 2016 we script out the DRI Table Order down below
$scripter.Options.XmlIndexes = $true
# Set scripter options to ensure only schema is scripted
$scripter.Options.ScriptSchema = $true;
$scripter.Options.ScriptData = $false;
if ($myDatabase.Length -gt 0)
{
Write-Output ("Only scripting Database {0}"-f $myDatabase)
}
# -----------------------
# iterate over each DB
# -----------------------
foreach($sqlDatabase in $srv.databases)
{
# If only one database secified on the command-line, ignore/skip all others
if ($myDatabase.Length -gt 0)
{
if ($sqlDatabase.Name -ne $myDatabase) {continue}
}
# Skip System Databases
if ($sqlDatabase.Name -in ('Model','MSDB','TempDB','SSISDB','distribution','Master')) {continue}
# Skip Offline Databases (SMO still enumerates them, but cant retrieve the objects)
if ($sqlDatabase.Status -ne 'Normal')
{
Write-Output ("Skipping Offline: {0}" -f $sqlDatabase.Name)
continue
}
# Script out objects for each DB
$db = $sqlDatabase
$fixedDBName = $db.name.replace('[','')
$fixedDBName = $fixedDBName.replace(']','')
$output_path = "$BaseFolder\$SQLInstance\30 - DataBase Objects\$fixedDBname"
# paths
$DB_Path = "$output_path\"
$table_path = "$output_path\Tables\"
$TableTriggers_path = "$output_path\TableTriggers\"
$views_path = "$output_path\Views\"
$storedProcs_path = "$output_path\StoredProcedures\"
$udfs_path = "$output_path\UserDefinedFunctions\"
$textCatalog_path = "$output_path\FullTextCatalogs\"
$udtts_path = "$output_path\UserDefinedTableTypes\"
$DBTriggers_path = "$output_path\DBTriggers\"
$Schemas_path = "$output_path\Schemas\"
$Filegroups_path = "$output_path\Filegroups\"
$Sequences_path = "$output_path\Sequences\"
$Synonyms_path = "$output_path\Synonyms\"
$DBScoped_Configs_path = "$output_path\DBScopedConfigs\"
$DBScoped_Creds_path = "$output_path\DBScopedCredentials\"
$QueryStore_path = "$output_path\QueryStore\"
$DBEDS_path = "$output_path\ExternalDataSources\"
$DBExtFF_path = "$output_path\ExternalFileFormats\"
$DBSecPol_path = "$output_path\SecurityPolicies\"
$XMLSC_path = "$output_path\XMLSchemaCollections\"
$DBColumnEncryptionKey_path = "$output_path\ColumnEncryptionKeys\"
$DBColumnMasterKey_path = "$output_path\ColumnMasterKeys\"
$DBRole_path = "$output_path\DBRoles\"
# --------------------------------
# Start Exporting Database Objects
# --------------------------------
# Main DB Export Folder
if(!(test-path -path $DB_Path))
{
mkdir $DB_Path | Out-Null
}
# Export Main Database Itself with Files and FileGroups
Write-Output "$fixedDBName - Database"
$MainDB = $db | Where-object { -not $_.IsSystemObject }
$myoutputfile = $DB_Path + $fixedDBName + ".sql"
$MainDB.Script() | out-file -FilePath $myoutputfile -encoding ascii -Force
# 2016+ Only Features
if ($myver -like "13.0*" -or $myver -like "14.0*")
{
# Database Scoped Credentials
Write-Output "$fixedDBName - Database Scoped Credentials"
$DBScopedCreds = $db.DatabaseScopedCredentials
CopyObjectsToFiles $DBScopedCreds $DBScoped_Creds_path
# Database Scoped Configs
Write-Output "$fixedDBName - Database Scoped Configs"
if(!(test-path -path $DBScoped_Configs_path))
{
mkdir $DBScoped_Configs_path | Out-Null
}
$myDBScopedOutfile =$DBScoped_Configs_path+"\DBScopedConfigs.sql"
"Use "+$DB.Name+"; `r`n" | Out-File -filepath $myDBScopedOutfile -encoding ascii -force
"ALTER DATABASE SCOPED CONFIGURATION SET MAXDOP = "+$Db.Maxdop | Out-File -filepath $myDBScopedOutfile -encoding ascii -Append
"ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET MAXDOP = " +$db.MaxDopForSecondary | Out-File -filepath $myDBScopedOutfile -encoding ascii -Append
"ALTER DATABASE SCOPED CONFIGURATION SET LEGACY_CARDINALITY_ESTIMATION = "+$db.LegacyCardinalityEstimation | Out-File -filepath $myDBScopedOutfile -encoding ascii -Append
"ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET LEGACY_CARDINALITY_ESTIMATION = "+$db.LegacyCardinalityEstimationForSecondary | Out-File -filepath $myDBScopedOutfile -encoding ascii -Append
"ALTER DATABASE SCOPED CONFIGURATION SET PARAMETER_SNIFFING = "+$db.ParameterSniffing | Out-File -filepath $myDBScopedOutfile -encoding ascii -Append
"ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET PARAMETER_SNIFFING = "+$db.ParameterSniffingForSecondary | Out-File -filepath $myDBScopedOutfile -encoding ascii -Append
"ALTER DATABASE SCOPED CONFIGURATION SET QUERY_OPTIMIZER_HOTFIXES = "+$db.QueryOptimizerHotfixes | Out-File -filepath $myDBScopedOutfile -encoding ascii -Append
"ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET QUERY_OPTIMIZER_HOTFIXES = "+$db.QueryOptimizerHotfixesForSecondary | Out-File -filepath $myDBScopedOutfile -encoding ascii -Append
# QueryStore Options
Write-Output "$fixedDBName - Query Store Options"
$myoutputfile = $QueryStore_path + "Query_Store.sql"
$QueryStore = $db.QueryStoreOptions
if ($QueryStore -ne $null)
{
if(!(test-path -path $QueryStore_path))
{
mkdir $QueryStore_path | Out-Null
}
$QueryStore.Script() | out-file -FilePath $myoutputfile -append -encoding ascii
}
# External Data Sources
Write-Output "$fixedDBName - External Data Sources"
$DB_EDS = $db.ExternalDataSources
CopyObjectsToFiles $DB_EDS $DBEDS_path
# External File Formats
Write-Output "$fixedDBName - External File Formats"
$DBExtFF = $db.ExternalFileFormats
CopyObjectsToFiles $DBExtFF $DBExtFF_path
# Security Policies
Write-Output "$fixedDBName - Database Security Policies"
$DBSecPol = $db.SecurityPolicies
CopyObjectsToFiles $DBSecPol $DBSecPol_path
# XMLSchema Collections
Write-Output "$fixedDBName - XML Schema Collections"
$DBXML_SC = $db.XmlSchemaCollections
CopyObjectsToFiles $DBXML_SC $XMLSC_path
# Always Encrypted Column Encryption Keys
Write-Output "$fixedDBName - Column Encryption Keys"
$DBAE_CEK = $db.ColumnEncryptionKeys
CopyObjectsToFiles $DBAE_CEK $DBColumnEncryptionKey_path
# Always Encrypted Column Master Keys
Write-Output "$fixedDBName - Column Master Keys"
$DBAE_CMK = $db.ColumnMasterKeys
CopyObjectsToFiles $DBAE_CMK $DBColumnMasterKey_path
}
# Create Settings Path
$DBSettingsPath = $output_path+"\Settings"
if(!(test-path -path $DBSettingsPath))
{
mkdir $DBSettingsPath | Out-Null
}
# Database Settings
Write-Output "$fixedDBName - Settings"
$mySettings = $db.Properties
$myoutputfile4 = $DBSettingsPath+"\Database_Settings.html"
$myHtml1 = $mySettings | sort-object Name | select Name, Value | ConvertTo-Html -Fragment -as table -PreContent "<h3>Database Settings for: $SQLInstance </h3>"
Convertto-Html -head $head -Body "$myHtml1" -Title "Database Settings" -PostContent "<h3>Ran on : $RunTime</h3>" | Set-Content -Path $myoutputfile4
# DBRoles
Write-Output "$fixedDBName - Roles"
# Create Output Sub Folder
if(!(test-path -path $DBRole_path))
{
mkdir $DBRole_path | Out-Null
}
# Get Role Properties and Members
foreach ($role in $db.Roles)
{
# Create Role File
$RoleFile = $DBRole_path+$role.name+".sql"
$RoleName = $role.Name
"Use "+$db.name | out-file $RoleFile -Encoding ascii -Append
"GO " | out-file $RoleFile -Encoding ascii -Append
" " | out-file $RoleFile -Encoding ascii -Append
"CREATE ROLE "+$RoleName | out-file $RoleFile -Encoding ascii -Append
" " | out-file $RoleFile -Encoding ascii -Append
foreach ($Roleproperty in $role.Properties)
{
"--- Role Property {0}={1}" -f $RoleProperty.name,$RoleProperty.value | out-file $RoleFile -Encoding ascii -Append
}
" " | out-file $RoleFile -Encoding ascii -Append
$RolePermissions = $role.EnumObjectPermissions()
foreach ($RolePermission in $RolePermissions)
{
"Role Permission {0}={1}" -f $RoleProperty.name,$RoleProperty.value | out-file $RoleFile -Encoding ascii -Append
}
"---Members:" | out-file $RoleFile -Encoding ascii -Append
$members = $role.EnumMembers()
foreach ($member in $members)
{
"EXEC sp_addrolemember '$RoleName','$member'" | out-file $RoleFile -Encoding ascii -Append
}
}
# Tables
Write-Output "$fixedDBName - Tables"
if ($mytable.Length -gt 0 -and $myDatabase -eq $sqldatabase.name)
{
Write-Output ("Only for table {0}"-f $mytable)
$tblSchema = ($mytable -split {$_ -eq "."})[0]
$tblTable = ($mytable -split {$_ -eq "."})[1]
$tbl = $db.Tables | Where-Object {$_.schema -eq $tblSchema -and $_.name -eq $tblTable}
}
else
# Get all Tables
{
$tbl = $db.Tables | Where-object { -not $_.IsSystemObject }
}
CopyObjectsToFiles $tbl $table_path
# Stored Procs
Write-Output "$fixedDBName - Stored Procs"
$storedProcs = $db.StoredProcedures | Where-object {-not $_.IsSystemObject }
CopyObjectsToFiles $storedProcs $storedProcs_path
# Views
Write-Output "$fixedDBName - Views"
$views = $db.Views | Where-object { -not $_.IsSystemObject }
CopyObjectsToFiles $views $views_path
# UDFs
Write-Output "$fixedDBName - UDFs"
$udfs = $db.UserDefinedFunctions | Where-object { -not $_.IsSystemObject }
CopyObjectsToFiles $udfs $udfs_path
# Table Types
Write-Output "$fixedDBName - Table Types"
$udtts = $db.UserDefinedTableTypes
CopyObjectsToFiles $udtts $udtts_path
# FullTextCats
Write-Output "$fixedDBName - FullTextCatalogs"
$catalog = $db.FullTextCatalogs
CopyObjectsToFiles $catalog $textCatalog_path
# DB Triggers
Write-Output "$fixedDBName - Database Triggers"
$DBTriggers = $db.Triggers
CopyObjectsToFiles $DBTriggers $DBTriggers_path
# Schemas
Write-Output "$fixedDBName - Schemas"
$Schemas = $db.Schemas | Where-object { -not $_.IsSystemObject }
CopyObjectsToFiles $Schemas $Schemas_path
# Sequences
Write-Output "$fixedDBName - Sequences"
$Sequences = $db.Sequences
CopyObjectsToFiles $Sequences $Sequences_path
# Synonyms
Write-Output "$fixedDBName - Synonyms"
$Synonyms = $db.Synonyms
CopyObjectsToFiles $Synonyms $Synonyms_path
# List Filegroups, Files and Path
Write-Output "$fixedDBName - FileGroups"
# Process FileGroups
$myoutputfile = $Filegroups_path+"Filegroups.txt"
if(!(test-path -path $Filegroups_path))
{
mkdir $Filegroups_path | Out-Null
}
# Create Output File
out-file -filepath $myoutputfile -encoding ascii -Force
Add-Content -path $myoutputfile -value "FileGroupName: DatabaseFileName: FilePath:"
# Prep SQL for Filegroups
$sqlCMD3 = "USE $db; SELECT `
cast(sysFG.name as char(24)) AS FileGroupName,
cast(dbfile.name as char(28)) AS DatabaseFileName,
dbfile.physical_name AS DatabaseFilePath
FROM
sys.database_files AS dbfile
INNER JOIN
sys.filegroups AS sysFG
ON
dbfile.data_space_id = sysFG.data_space_id
order by dbfile.file_id
"
# Run SQL
if ($serverauth -eq "win")
{
$sqlresults3 = ConnectWinAuth -SQLInstance $SQLInstance -Database "master" -SQLExec $sqlCMD3
}
else
{
$sqlresults3 = ConnectSQLAuth -SQLInstance $SQLInstance -Database "master" -SQLExec $sqlCMD3 -User $myuser -Password $mypass
}
# Script Out
foreach ($FG in $sqlresults3)
{
$myoutputstring = $FG.FileGroupName+$FG.DatabaseFileName+$FG.DatabaseFilePath
$myoutputstring | out-file -FilePath $myoutputfile -append -encoding ascii -width 500
}
# Table Creation in Dependency Order to maintain DRI
Write-Output "$fixedDBName - DRI Create Table Order"
# Create Database Summary Listing
$sqlCMD4 =
"
use $fixedDBName;
--- Reference/Credit:
--- http://stackoverflow.com/questions/352176/sqlserver-how-to-sort-table-names-ordered-by-their-foreign-key-dependency
---
declare @level int -- Current depth
declare @count int
-- Table Variables
declare @Tables TABLE (
[TableName] [nvarchar](257) NOT NULL,
[TableID] [int] NOT NULL,
[Ordinal] [int] NOT NULL
)
-- Step 1: Start with tables that have no FK dependencies
insert into @Tables
select s.name + '.' + t.name as TableName
,t.object_id as TableID
,0 as Ordinal
from sys.tables t
join sys.schemas s
on t.schema_id = s.schema_id
where not exists
(select 1
from sys.foreign_keys f
where f.parent_object_id = t.object_id)
set @count = @@rowcount
set @level = 0
-- Step 2: For a given depth this finds tables joined to
-- tables at this given depth. A table can live at multiple
-- depths if it has more than one join path into it, so we
-- filter these out in step 3 at the end.
--
while @count > 0 begin
insert @Tables (
TableName
,TableID
,Ordinal
)
select s.name + '.' + t.name as TableName
,t.object_id as TableID
,@level + 1 as Ordinal
from sys.tables t
join sys.schemas s
on s.schema_id = t.schema_id
where exists
(select 1
from sys.foreign_keys f
join @Tables tt
on f.referenced_object_id = tt.TableID
and tt.Ordinal = @level
and f.parent_object_id = t.object_id
and f.parent_object_id != f.referenced_object_id)
-- The last line ignores self-joins. You'll
-- need to deal with these separately
set @count = @@rowcount
set @level = @level + 1
end
-- Step 3: This filters out the maximum depth an object occurs at
-- and displays the deepest first.
--
select t.Ordinal
--,t.TableID
,t.TableName
from @Tables t
join (select TableName as TableName
,Max (Ordinal) as Ordinal
from @Tables
group by TableName) tt
on t.TableName = tt.TableName
and t.Ordinal = tt.Ordinal
order by t.Ordinal desc
"
# Run SQL
if ($serverauth -eq "win")
{
$sqlresults4 = ConnectWinAuth -SQLInstance $SQLInstance -Database "master" -SQLExec $sqlCMD4
}
else
{
$sqlresults4 = ConnectSQLAuth -SQLInstance $SQLInstance -Database "master" -SQLExec $sqlCMD4 -User $myuser -Password $mypass
}
$RunTime = Get-date
$FullFolderPath = "$BaseFolder\$SQLInstance\30 - DataBase Objects\"
if(!(test-path -path $FullFolderPath))
{
mkdir $FullFolderPath | Out-Null
}
"Create Your Tables in this order to maintain Declarative Referential Integrity`r`n" | out-file "$output_path\DRI_Table_Creation_Order.txt" -Encoding ascii
$sqlresults4 | select Ordinal, TableName | out-file "$output_path\DRI_Table_Creation_Order.txt" -Encoding ascii -Append
# -------------------------------------------------------------------------
# Force GC
# March 10, 2015 - can we manually kick off a GC pass?
# Tested with Perfmon - GC has a delay in releasing memory as the allocations bubble up the generations, AKA, its slow
# Seems only ending the script/session releases memory
# Release Memory Benchmarking - Test setting a variable to $null vs using Remove-Variable
# -------------------------------------------------------------------------
$tbl = $null
$storedProcs = $null
$views = $null
$udfs = $null
$udtts = $null
$catalog = $null
$DBTriggers = $null
$TableTriggers = $null
$Schemas = $null
$Sequences = $null
$Synonyms = $null
[System.GC]::Collect()
}
# Return To Base
set-location $BaseFolder