-
Notifications
You must be signed in to change notification settings - Fork 24
/
Backup-Database.ps1
256 lines (217 loc) · 8.15 KB
/
Backup-Database.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
<#
.SYNOPSIS
SQL Server Backup Database / Log Script
.DESCRIPTION
SQL Server のデータベース / トランザクションログのバックアップを取得します。
開発環境 :
Windows Server 2016 + Windows PowerShell (5.1)
Ubuntu 16.04 + PowerShell Core (6.1.0-preview.2)
.EXAMPLE
./Backup-Database.ps1 -ServerInstance <SQL Server 名> -Username <SQL Login> -P <Login Password> -RunSpaceSize 5
.LINK
- PowerShell による同期処理、非同期処理、並列処理 を考えてみる
http://tech.guitarrapc.com/entry/2013/10/29/100946
- RunspacePoolを使って、PowerShellを非同期実行
https://www.gmo.jp/report/single/?art_id=195
- Weekend Scripter: Max Out PowerShell in a Little Bit of Time—Part 2
https://blogs.technet.microsoft.com/heyscriptingguy/2013/09/29/weekend-scripter-max-out-powershell-in-a-little-bit-of-timepart-2/
- Beginning Use of PowerShell Runspaces: Part 1
https://blogs.technet.microsoft.com/heyscriptingguy/2015/11/26/beginning-use-of-powershell-runspaces-part-1/
#>
[CmdletBinding()]
Param(
[int]$CommandTimeout = 600,
[int]$ConnectionTimeout = 15,
[int]$RunspaceSize = 2,
[Parameter(Mandatory=$True)]
[string]$ServerInstance,
[Parameter(Mandatory=$True)]
[string]$Username,
[Parameter(Mandatory=$True)]
[string]$Password,
[string]$BackupPath = ".",
[switch]$Log
)
##### Function definition ####
function Out-Message([string]$Msg){
Write-Host ("[{0}] $Msg" -f (Get-Date).ToString("yyyy/MM/dd HH:mm:ss.fff"), $Msg)
}
############################
$ErrorActionPreference = "Stop"
$success = 0
$failed = 0
$TargetDatabaseQuery = @"
USE [master];
SET NOCOUNT ON;
SELECT
name,
create_date,
recovery_model,
recovery_model_desc,
D AS full_backup_finish_date,
I AS diff_backup_finish_date,
L AS log_backup_finish_date
FROM
(
SELECT
d.database_id,
d.name,
d.create_date,
d.recovery_model,
d.recovery_model_desc,
backup_tbl.type,
backup_tbl.backup_finish_date
FROM
sys.databases AS d
LEFT JOIN
(SELECT
database_name,
type,
MAX(backup_finish_date) AS backup_finish_date
FROM
msdb.dbo.backupset
GROUP BY
database_name,
type
) AS backup_tbl
ON
d.name = backup_tbl.database_name
) AS T
PIVOT
(
MAX(backup_finish_date)
FOR type IN(D, I, L)
)AS PVT
ORDER BY
database_id ASC
"@
Out-Message -Msg ("=" * 20)
Out-Message "Script Settings:"
Out-Message ("Connection Timeout:[{0}] / Command Timeout:[{1}] / Runspace Size:[{2}]" -f $ConnectionTimeout, $CommandTimeout, $RunspaceSize)
Out-Message -Msg ("=" * 20)
Out-Message "Backup $(if($Log){"Log "}else{"Database "})start."
$sw = [system.diagnostics.stopwatch]::startNew()
$constring = New-Object System.Data.SqlClient.SqlConnectionStringBuilder
$constring.psbase.DataSource = $ServerInstance
$constring.psbase.InitialCatalog = "master"
$constring.psbase.UserID = $Username
$constring.psbase.Password = $Password
$constring.psbase.ConnectTimeout = $ConnectionTimeout
$con = New-Object System.Data.SqlClient.SqlConnection
$con.ConnectionString = $constring
$con.Open()
$cmd = $con.CreateCommand()
$cmd.CommandText = $TargetDatabaseQuery
$da = New-Object System.Data.SqlClient.SqlDataAdapter
$da.SelectCommand = $cmd
$ds = New-Object System.Data.DataSet
[void]$da.Fill($ds)
$con.Close()
$con.Dispose()
try{
$minpoolsize = $maxpoolsize = $RunspaceSize
$runspacePool = [runspacefactory]::CreateRunspacePool($minPoolSize, $maxPoolSize)
# Linux の PowerShell Core では、ApartmentState の設定ができなかったため、Windows PowerShell を対象に STA 設定
if($PSVersionTable.PSEdition -eq "Desktop"){
$runspacePool.ApartmentState = "STA"
}
$runspacePool.Open()
$Command = {
Param(
[string]$constring,
[string]$dbname,
[string]$backupsql,
[int]$CommandTimeout
)
try{
$orgErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
$con = New-Object System.Data.SqlClient.SqlConnection
$con.ConnectionString = $constring
$con.Open()
$cmd = $con.CreateCommand()
$cmd.CommandTimeout = $CommandTimeout
$cmd.CommandText = $backupsql
[void]$cmd.ExecuteNonQuery()
$cmd.Dispose()
Write-Output ("Backup Success [{0}] " -f $dbname)
}catch{
return $Error[0]
}finally{
if($con -ne $null){
$con.Close()
$con.Dispose()
}
$ErrorActionPreference = $orgErrorActionPreference
}
}
$RunspaceCollection = New-Object System.Collections.ArrayList
$Result = New-Object System.Collections.ArrayList
foreach ($row in $ds.Tables[0].Rows){
# tempdb はバックアップが取得できないため処理対象外とする
if ($row["name"] -notcontains ("tempdb")){
# Transaction Log Backup
if ($Log){
$backupfile = Join-Path -Path $BackupPath -ChildPath (($row["name"] + "_" + (Get-Date).ToString("yyyyMMdd")) + ".trn")
$backupfile = $backupfile -replace "\\" , "/"
$backupsql = "BACKUP LOG {0} TO DISK=N'{1}' WITH COMPRESSION, STATS=5" -f $row["name"], $backupfile
# Database Full Backup
}else{
$backupfile = Join-Path -Path $BackupPath -ChildPath (($row["name"] + "_" + (Get-Date).ToString("yyyyMMdd")) + ".bak")
$backupfile = $backupfile -replace "\\" , "/"
$backupsql = "BACKUP DATABASE {0} TO DISK=N'{1}' WITH COMPRESSION, STATS=5" -f $row["name"], $backupfile
}
# 単純復旧 / 初回完全バックアップが取得されていない場合、ログバックアップはスキップ
if (!(($row.recovery_model -eq 3 -or [String]::IsNullOrEmpty($row.full_backup_finish_date)) -and $Log)){
$powershell = [PowerShell]::Create().AddScript($Command).AddArgument($constring.ConnectionString).AddArgument($row["name"]).AddArgument($backupsql).AddArgument($CommandTimeout)
$powershell.RunspacePool = $runspacePool
Out-Message -Msg ("Available Runspaces in RunspacePool: [{0}]" -f $RunspacePool.GetAvailableRunspaces())
[void]$RunspaceCollection.Add([PSCustomObject] @{
Runspace = $powershell.BeginInvoke();
PowerShell = $powershell
DBName = $row["name"]
BackupFile = $backupfile
StartTime = Get-Date
})
Out-Message -Msg ("[{0}] Backup waiting." -f $row["name"])
}
}
}
# 処理完了の待機
while($RunspaceCollection){
foreach($runspace in $RunspaceCollection){
if ($runspace.Runspace.IsCompleted){
$ret = $runspace.powershell.EndInvoke($runspace.Runspace)
$runspace.PowerShell.Dispose()
if (($ret | Get-Member).TypeName[0] -eq [System.Management.Automation.ErrorRecord]){
Out-Message -Msg ("[{0}] Backup failed : {1} (Start:[{2}] / End:[{3}])" -f $runspace.DBName, $ret.Exception.Message, $runspace.StartTime, (Get-Date))
$failed +=1
}else{
Out-Message -Msg ("[{0}] Backup completed (File:[{1}] / Start:[{2}] / End:[{3}])" -f $runspace.DBName, $runspace.BackupFile, $runspace.StartTime, (Get-Date))
$success +=1
}
[void]$Result.Add($ret)
$RunspaceCollection.Remove($runspace)
break
}
}
Start-Sleep -Milliseconds 100
}
}catch{
Write-Output $Error[0]
}finally{
if ($runspacePool -ne $null){
$runspacePool.Close()
$runspacePool.Dispose()
}
}
$ds.Dispose()
$da.Dispose()
$con.Close()
$con.Dispose()
$sw.Stop()
Out-Message -Msg ("Backup $(if($Log){"Log "}else{"Database "})End.")
Out-Message -Msg ("=" * 20)
Out-Message -Msg ("Total execution time (sec) : [{0}]" -f $sw.Elapsed.TotalSeconds)
Out-Message -Msg ("[Result] Success : [{0}] / Failed : [{1}]" -f $success, $failed)
Out-Message -Msg ("=" * 20)