-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20_DataBase_Objects.ps1
More file actions
717 lines (581 loc) · 23.3 KB
/
20_DataBase_Objects.ps1
File metadata and controls
717 lines (581 loc) · 23.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
<#
.SYNOPSIS
Gets the core Database Objects on the target server
.DESCRIPTION
Writes the Objects out into subfolders in the "20 - 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
20_DataBase_Objects.ps1 localhost
.EXAMPLE
20_DataBase_Objects.ps1 server01 sa password
.EXAMPLE
20_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 (needs the Database parameter too)
.LINK
#>
Param(
[string]$SQLInstance = "localhost",
[string]$myuser,
[string]$mypass,
[string]$myDatabase,
[string]$mytable
)
Set-StrictMode -Version latest;
$DebugPreference = "Stop"
[string]$BaseFolder = (Get-Item -Path ".\" -Verbose).FullName
Write-Host -f Yellow -b Black "20 - DataBase Objects (Triggers, Tables, Views, Procs, UDFs, FullTextCats, TableTypes, Schemas)"
# Load SMO Assemblies
Import-Module ".\LoadSQLSmo.psm1"
LoadSQLSMO
# Usage Check
if ($SQLInstance.Length -eq 0)
{
Write-host -f yellow "Usage: ./20_DataBase_Objects.ps1 `"SQLServerName`" ([`"Username`"] [`"Password`"] if DMZ machine)"
exit
}
# Parameter check: Table needs Database
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
}
# Working
Write-Output "Server $SQLInstance"
# Server connection check
try
{
$old_ErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'
if ($mypass.Length -ge 1 -and $myuser.Length -ge 1)
{
Write-Output "Testing SQL Auth"
# .NET Method
# Open connection and Execute sql against server
$DataSet = New-Object System.Data.DataSet
$SQLConnectionString = "Data Source=$SQLInstance;User ID=$myuser;Password=$mypass;"
$Connection = New-Object System.Data.SqlClient.SqlConnection
$Connection.ConnectionString = $SQLConnectionString
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "select serverproperty('productversion')"
$SqlCmd.Connection = $Connection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
# Insert results into Dataset table
$SqlAdapter.Fill($DataSet) | out-null
# Close connection to sql server
$Connection.Close()
$results = $DataSet.Tables[0].Rows[0]
# SQLCMD.EXE Method
#$results = Invoke-SqlCmd -ServerInstance $SQLInstance -Query "select serverproperty('productversion')" -Username $myuser -Password $mypass -QueryTimeout 10 -erroraction SilentlyContinue
$serverauth="sql"
}
else
{
Write-Output "Testing Windows Auth"
# .NET Method
# Open connection and Execute sql against server using Windows Auth
$DataSet = New-Object System.Data.DataSet
$SQLConnectionString = "Data Source=$SQLInstance;Integrated Security=SSPI;"
$Connection = New-Object System.Data.SqlClient.SqlConnection
$Connection.ConnectionString = $SQLConnectionString
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "select serverproperty('productversion')"
$SqlCmd.Connection = $Connection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
# Insert results into Dataset table
$SqlAdapter.Fill($DataSet) | out-null
# Close connection to sql server
$Connection.Close()
$results = $DataSet.Tables[0].Rows[0]
# SQLCMD.EXE Method
#$results = Invoke-SqlCmd -ServerInstance $SQLInstance -Query "select serverproperty('productversion')" -QueryTimeout 10 -erroraction SilentlyContinue
$serverauth = "win"
}
if($results -ne $null)
{
Write-Output ("SQL Version: {0}" -f $results.Column1)
}
# Reset default PS error handler
$ErrorActionPreference = $old_ErrorActionPreference
}
catch
{
Write-Host -f red "$SQLInstance appears offline - Try Windows Authorization."
Set-Location $BaseFolder
exit
}
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
}
}
}
}
# Set Local Vars
$server = $SQLInstance
if ($serverauth -eq "win")
{
$srv = New-Object "Microsoft.SqlServer.Management.SMO.Server" $server
$scripter = New-Object ("Microsoft.SqlServer.Management.SMO.Scripter") ($server)
}
else
{
$srv = New-Object "Microsoft.SqlServer.Management.SMO.Server" $server
$srv.ConnectionContext.LoginSecure=$false
$srv.ConnectionContext.set_Login($myuser)
$srv.ConnectionContext.set_Password($mypass)
$scripter = New-Object ("Microsoft.SqlServer.Management.SMO.Scripter") ($srv)
}
# Db and Table Objects
#$db = New-Object ("Microsoft.SqlServer.Management.SMO.Database")
#$tbl = New-Object ("Microsoft.SqlServer.Management.SMO.Table")
# Set Speed=On trick - doesnt work on Scripting - But thanks for the tip MVP Ben Miller
# $tbl.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.Table], "CreateDate")
# Find/Inspect other Server-Level Objects here
Write-Output "Looking for Objects..."
# Create some CSS for help in HTML formatting
$myCSS =
"
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;
}
"
# Create Database Summary Listing
$mySQLquery =
"
SELECT
DB_NAME([database_id]) AS [Database_Name],
[file_id],
name as 'Name',
physical_name as 'FileName',
type_desc as 'Type',
state_desc as 'State',
case when is_percent_growth=1 then '%' else 'MB' end as 'Growth',
case when is_percent_growth=1 then growth else CONVERT(float, growth/128.0) end AS [Growth_in_MB],
CONVERT(float, size/128.0) AS [DB_Size_in_MB]
FROM sys.master_files WITH (NOLOCK)
ORDER BY DB_NAME([database_id]) OPTION (RECOMPILE);
"
#Run SQL
if ($serverauth -eq "win")
{
# .Net Method
# Open connection and Execute sql against server using Windows Auth
$DataSet = New-Object System.Data.DataSet
$SQLConnectionString = "Data Source=$SQLInstance;Integrated Security=SSPI;"
$Connection = New-Object System.Data.SqlClient.SqlConnection
$Connection.ConnectionString = $SQLConnectionString
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $mySQLquery
$SqlCmd.Connection = $Connection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
# Insert results into Dataset table
$SqlAdapter.Fill($DataSet) |out-null
# Close connection to sql server
$Connection.Close()
$sqlresultsX = $DataSet.Tables[0].Rows
# SQLCMD.EXE Method
#$sqlresultsX = Invoke-SqlCmd -ServerInstance $SQLInstance -Query $mySQLquery -QueryTimeout 10 -erroraction SilentlyContinue
}
else
{
# .Net Method
# Open connection and Execute sql against server
$DataSet = New-Object System.Data.DataSet
$SQLConnectionString = "Data Source=$SQLInstance;User ID=$myuser;Password=$mypass;"
$Connection = New-Object System.Data.SqlClient.SqlConnection
$Connection.ConnectionString = $SQLConnectionString
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $mySQLquery
$SqlCmd.Connection = $Connection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
# Insert results into Dataset table
$SqlAdapter.Fill($DataSet) |out-null
# Close connection to sql server
$Connection.Close()
$sqlresultsX = $DataSet.Tables[0].Rows
# SQLCMD.EXE Method
#$sqlresultsX = Invoke-SqlCmd -ServerInstance $SQLInstance -Query $mySQLquery -Username $myuser -Password $mypass -QueryTimeout 10 -erroraction SilentlyContinue
}
$RunTime = Get-date
$FullFolderPath = "$BaseFolder\$SQLInstance\20 - DataBase Objects\"
if(!(test-path -path $FullFolderPath))
{
mkdir $FullFolderPath | Out-Null
}
$myCSS | out-file "$FullFolderPath\HTMLReport.css" -Encoding ascii
$sqlresultsX | select Database_Name,file_id, Name, FileName, Type, State, growth, growth_in_mb, DB_Size_in_MB | ConvertTo-Html -PreContent "<h1>$SqlInstance</H1><H2>Database Summary</h2>" -PostContent "<h3>Ran on : $RunTime</h3>" -CSSUri "HtmlReport.css"| Set-Content "$FullFolderPath\Database_Summary.html"
# 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 create one huge file for all tables in the order needed to maintain RefIntegrity
$scripter.Options.WithDependencies = $false # Leave OFF - creates issues
$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 for 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 'Master','Model','MSDB','TempDB','SSISDB') {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\20 - 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\"
#Get Objects via SMO into PS Objects
# Mar 10, 2015 - OK this is where .NET gobbles memory, so switch to this:
# 1) Load objects from server
# 2) Write objects to disk file
# 3) Set variables to null
# 4) Let GC (hopefully) do its nefarious job of cleanup
# 5) Does it work? Testing a batch file running against 22 SQL servers still uses about 16Gigs 'O Ram, even though the ps1 files are called in a chain,
# giving GC a chance to release memory between powershell.exe sessions, but it doesnt.
# Swell.
<#
Write-Output "Starting Memory: $db"
[System.gc]::gettotalmemory("forcefullcollection") /1MB
ps powershell* | Select *memory* | ft -auto `
@{Name='VirtualMemMB';Expression={($_.VirtualMemorySize64)/1MB}}, `
@{Name='PrivateMemMB';Expression={($_.PrivateMemorySize64)/1MB}}
#>
# Export Database Properties
$DBSettingsPath = $output_path+"\Settings"
if(!(test-path -path $DBSettingsPath))
{
mkdir $DBSettingsPath | Out-Null
}
# Export Main Database Itself with Files and FileGroups
Write-Output "$fixedDBName - Database"
$MainDB = $db | Where-object { -not $_.IsSystemObject }
CopyObjectsToFiles $MainDB $DB_Path
# Create Database Object Reconstruction Order Hints File
"Database Object Reconstruction Order" | out-file "$output_path\Database_Reconstruction_Order.txt" -Encoding ascii -Append
"`n " | out-file "$output_path\Database_Reconstruction_Order.txt" -Encoding ascii -Append
"01) Database with Filegroups" | out-file "$output_path\Database_Reconstruction_Order.txt" -Encoding ascii -Append
"02) .NET Assemblies" | out-file "$output_path\Database_Reconstruction_Order.txt" -Encoding ascii -Append
"03) Linked Servers" | out-file "$output_path\Database_Reconstruction_Order.txt" -Encoding ascii -Append
"04) Logins" | out-file "$output_path\Database_Reconstruction_Order.txt" -Encoding ascii -Append
"05) Sequences" | out-file "$output_path\Database_Reconstruction_Order.txt" -Encoding ascii -Append
"06) Synonyms" | out-file "$output_path\Database_Reconstruction_Order.txt" -Encoding ascii -Append
"07) Schemas" | out-file "$output_path\Database_Reconstruction_Order.txt" -Encoding ascii -Append
"08) UDFs (Table-Valued and Scalar Functions)" | out-file "$output_path\Database_Reconstruction_Order.txt" -Encoding ascii -Append
"09) User-Defined Table Types" | out-file "$output_path\Database_Reconstruction_Order.txt" -Encoding ascii -Append
"10) Tables" | out-file "$output_path\Database_Reconstruction_Order.txt" -Encoding ascii -Append
"11) Views" | out-file "$output_path\Database_Reconstruction_Order.txt" -Encoding ascii -Append
"12) Stored Procedures" | out-file "$output_path\Database_Reconstruction_Order.txt" -Encoding ascii -Append
"13) Full-Text Catalogs" | out-file "$output_path\Database_Reconstruction_Order.txt" -Encoding ascii -Append
"14) Table Triggers" | out-file "$output_path\Database_Reconstruction_Order.txt" -Encoding ascii -Append
"15) Database Triggers" | out-file "$output_path\Database_Reconstruction_Order.txt" -Encoding ascii -Append
# Create CSS file
$myCSS | out-file "$DBSettingsPath\HTMLReport.css" -Encoding ascii
# Export DB Settings
Write-Output "$fixedDBName - Settings"
$mySettings = $db.Properties
$mySettings | sort-object Name | select Name, Value | ConvertTo-Html -CSSUri "$DBSettingsPath\HTMLReport.css"| Set-Content "$DBSettingsPath\HtmlReport.html"
# -------------------------
# Start Individual Objects
# -------------------------
# 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
# Create output folder
$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
$mySQLquery = "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")
{
# .Net Method
# Open connection and Execute sql against server using Windows Auth
$DataSet = New-Object System.Data.DataSet
$SQLConnectionString = "Data Source=$SQLInstance;Integrated Security=SSPI;"
$Connection = New-Object System.Data.SqlClient.SqlConnection
$Connection.ConnectionString = $SQLConnectionString
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $mySQLquery
$SqlCmd.Connection = $Connection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
# Insert results into Dataset table
$SqlAdapter.Fill($DataSet) |out-null
# Close connection to sql server
$Connection.Close()
$sqlresults2 = $DataSet.Tables[0].Rows
# SQLCMD.EXE Method
# $sqlresults2 = Invoke-SqlCmd -ServerInstance $SQLInstance -Query $mySQLquery -QueryTimeout 10 -erroraction SilentlyContinue
}
else
{
# .Net Method
# Open connection and Execute sql against server
$DataSet = New-Object System.Data.DataSet
$SQLConnectionString = "Data Source=$SQLInstance;User ID=$myuser;Password=$mypass;"
$Connection = New-Object System.Data.SqlClient.SqlConnection
$Connection.ConnectionString = $SQLConnectionString
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $mySQLquery
$SqlCmd.Connection = $Connection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
# Insert results into Dataset table
$SqlAdapter.Fill($DataSet) |out-null
# Close connection to sql server
$Connection.Close()
$sqlresults2 = $DataSet.Tables[0].Rows
# $sqlresults2 = Invoke-SqlCmd -ServerInstance $SQLInstance -Query $mySQLquery -Username $myuser -Password $mypass -QueryTimeout 10 -erroraction SilentlyContinue
}
# Script Out
foreach ($FG in $sqlresults2)
{
$myoutputstring = $FG.FileGroupName+$FG.DatabaseFileName+$FG.DatabaseFilePath
$myoutputstring | out-file -FilePath $myoutputfile -append -encoding ascii -width 500
}
# Force GC
# March 10, 2015 - can we manually kick off a GC pass?
# Testing with Perfmon
# Seems only ending the script/session releases memory
# Release Memory - Test Setting a variable to $null vs Remove-Variable
$tbl = $null
$storedProcs = $null
$views = $null
$udfs = $null
$udtts = $null
$catalog = $null
$DBTriggers = $null
$TableTriggers = $null
$Schemas = $null
$Sequences = $null
$Synonyms = $null
<#
Remove-Variable $tbl
Remove-Variable $storedProcs
Remove-Variable $views
Remove-Variable $udfs
Remove-Variable $udtts
Remove-Variable $catalog
Remove-Variable $DBTriggers
Remove-Variable $TableTriggers
Remove-Variable $Schemas
Remove-Variable $Sequences
Remove-Variable $Synonyms
#>
[System.GC]::Collect()
<#
Write-Output "Ending Memory: $db"
[System.gc]::gettotalmemory("forcefullcollection") /1MB
ps powershell* | Select *memory* | ft -auto `
@{Name='VirtualMemMB';Expression={($_.VirtualMemorySize64)/1MB}}, `
@{Name='PrivateMemMB';Expression={($_.PrivateMemorySize64)/1MB}}
#>
# Process Other Objecs
# Process Next Database
}
# finish
set-location $BaseFolder