-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathBuild-AttachSQL.ps1
51 lines (38 loc) · 1.48 KB
/
Build-AttachSQL.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
<#
.SYNOPSIS
<A brief description of the script>
.DESCRIPTION
<A detailed description of the script>
.PARAMETER <paramName>
<Description of script parameter>
.EXAMPLE
<An example of using the script>
#>
param([parameter(Mandatory=$true)][string] $dir,
[parameter(Mandatory=$true)][string] $server)
#load assemblies
Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
$smosrv = new-object ('Microsoft.SqlServer.Management.Smo.Server') $server
#get backup files
$files = gci $dir | where {$_.name -like "*.bak"}
$output=([Environment]::GetFolderPath("MyDocuments")) + "\attachdbs.sql"
"/*****************************************" > $output
"Attach script based off of backup files" >> $output
"*****************************************/" >> $output
foreach($file in $files){
$rs=new-object("Microsoft.SqlServer.Management.Smo.Restore")
$rs.Devices.AddDevice($file.FullName, "File")
$hd=$rs.ReadBackupHeader($smosrv)
$dbname=$hd.Rows[0].DatabaseName
$dbfiles=$rs.ReadFileList($smosrv)
"CREATE DATABASE $dbname ON" >> $output
$filewrite=@()
foreach($dbfile in $dbfiles){
$filewrite+="(FILENAME='"+$dbfile.PhysicalName+"')"
}
$filewrite -join ",`n" >> $output
"FOR ATTACH; `n--------------------------" >> $output
}