-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackup_module.ps1
More file actions
267 lines (219 loc) · 10.2 KB
/
backup_module.ps1
File metadata and controls
267 lines (219 loc) · 10.2 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
<#
BackupModule.ps1 - 系統備份模組
支援 EFI、MSR、Windows 分割區備份
Version: v0.2
#>
function Start-SystemBackup {
param(
[int]$DiskIndex,
[string]$BackupPath,
[scriptblock]$ProgressCallback,
[scriptblock]$LogCallback
)
$result = @{
Success = $false
BackupFile = $null
Error = $null
}
try {
# 呼叫日誌回調
if ($LogCallback) { & $LogCallback "開始分析磁碟 $DiskIndex..." }
# 獲取磁碟資訊
$disk = Get-Disk -Number $DiskIndex
if (-not $disk) {
throw "無法找到磁碟 $DiskIndex"
}
# 獲取分割區資訊
$partitions = Get-Partition -DiskNumber $DiskIndex | Sort-Object PartitionNumber
if ($LogCallback) { & $LogCallback "發現 $($partitions.Count) 個分割區" }
# 建立備份檔案名稱
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$backupFileName = "SystemBackup_Disk$($DiskIndex)_$timestamp.wim"
$backupFilePath = Join-Path $BackupPath $backupFileName
# 確保備份目錄存在
if (-not (Test-Path $BackupPath)) {
New-Item -Path $BackupPath -ItemType Directory -Force | Out-Null
if ($LogCallback) { & $LogCallback "建立備份目錄: $BackupPath" }
}
# 檢查可用空間
$driveInfo = Get-WmiObject -Class Win32_LogicalDisk | Where-Object { $_.DeviceID -eq ([System.IO.Path]::GetPathRoot($BackupPath)).TrimEnd('\') }
$availableSpaceGB = [math]::Round($driveInfo.FreeSpace / 1GB, 2)
$diskSizeGB = [math]::Round($disk.Size / 1GB, 2)
if ($LogCallback) { & $LogCallback "目標磁碟可用空間: $availableSpaceGB GB,來源磁碟大小: $diskSizeGB GB" }
if ($availableSpaceGB -lt ($diskSizeGB * 0.5)) {
if ($LogCallback) { & $LogCallback "警告: 可用空間可能不足,建議至少保留 50% 的來源磁碟空間" }
}
# 開始備份程序
if ($ProgressCallback) { & $ProgressCallback 10 }
# 分析每個分割區類型
$systemPartitions = @()
$dataPartitions = @()
foreach ($partition in $partitions) {
$partitionType = $partition.Type
$partitionSize = [math]::Round($partition.Size / 1MB, 2)
if ($LogCallback) { & $LogCallback "分割區 $($partition.PartitionNumber): $partitionType ($partitionSize MB)" }
switch ($partitionType) {
"System" {
$systemPartitions += $partition
if ($LogCallback) { & $LogCallback " -> EFI 系統分割區" }
}
"Reserved" {
$systemPartitions += $partition
if ($LogCallback) { & $LogCallback " -> MSR 保留分割區" }
}
"Basic" {
if ($partition.DriveLetter) {
$dataPartitions += $partition
if ($LogCallback) { & $LogCallback " -> 資料分割區 ($($partition.DriveLetter):)" }
} else {
$systemPartitions += $partition
if ($LogCallback) { & $LogCallback " -> 系統分割區 (無磁碟機代號)" }
}
}
default {
$systemPartitions += $partition
if ($LogCallback) { & $LogCallback " -> 其他系統分割區" }
}
}
}
if ($ProgressCallback) { & $ProgressCallback 20 }
# 使用 DISM 建立 WIM 映像檔
$config = Get-AppConfig
$dismPath = $config.DismPath
if (-not (Test-Path $dismPath)) {
throw "找不到 DISM 執行檔: $dismPath"
}
# 建立完整磁碟映像
if ($LogCallback) { & $LogCallback "開始建立磁碟映像..." }
# 使用 DISM 的 capture-image 功能
$windowsPartition = $dataPartitions | Where-Object { $_.DriveLetter -and (Test-Path "$($_.DriveLetter):\Windows") } | Select-Object -First 1
if ($windowsPartition) {
$sourceDrive = "$($windowsPartition.DriveLetter):"
if ($LogCallback) { & $LogCallback "發現 Windows 分割區: $sourceDrive" }
# 建立 Windows 映像
$dismArgs = @(
"/Capture-Image"
"/ImageFile:`"$backupFilePath`""
"/CaptureDir:$sourceDrive"
"/Name:`"SystemBackup_$timestamp`""
"/Description:`"Full System Backup created on $(Get-Date)`""
"/Compress:max"
"/CheckIntegrity"
)
if ($ProgressCallback) { & $ProgressCallback 30 }
$dismProcess = Start-Process -FilePath $dismPath -ArgumentList $dismArgs -Wait -PassThru -NoNewWindow -RedirectStandardOutput "$env:TEMP\dism_output.log" -RedirectStandardError "$env:TEMP\dism_error.log"
if ($dismProcess.ExitCode -ne 0) {
$errorLog = Get-Content "$env:TEMP\dism_error.log" -Raw
Add-LogEntry -Message "DISM 執行失敗 (錯誤碼: $($dismProcess.ExitCode))" -Level ERROR
Add-LogEntry -Message "DISM 錯誤輸出: $errorLog" -Level DEBUG
throw "DISM 執行失敗 (錯誤碼: $($dismProcess.ExitCode))"
}
if ($ProgressCallback) { & $ProgressCallback 70 }
if ($LogCallback) { & $LogCallback "Windows 分割區映像建立完成" }
} else {
throw "無法找到 Windows 分割區"
}
# 備份分割區表和 MBR/GPT 資訊
$partitionInfoFile = Join-Path $BackupPath "PartitionInfo_Disk$($DiskIndex)_$timestamp.json"
$diskInfo = @{
DiskNumber = $DiskIndex
PartitionStyle = $disk.PartitionStyle
Size = $disk.Size
Partitions = @()
Timestamp = Get-Date
}
foreach ($partition in $partitions) {
$partInfo = @{
PartitionNumber = $partition.PartitionNumber
Type = $partition.Type
Size = $partition.Size
Offset = $partition.Offset
DriveLetter = $partition.DriveLetter
IsActive = $partition.IsActive
IsBoot = $partition.IsBoot
IsSystem = $partition.IsSystem
}
$diskInfo.Partitions += $partInfo
}
$diskInfo | ConvertTo-Json -Depth 10 | Out-File -FilePath $partitionInfoFile -Encoding UTF8
if ($LogCallback) { & $LogCallback "分割區資訊已儲存: $partitionInfoFile" }
if ($ProgressCallback) { & $ProgressCallback 85 }
# 備份開機記錄 (僅適用於系統磁碟)
if ($disk.IsBoot -or $disk.IsSystem) {
$bootBackupFile = Join-Path $BackupPath "BootSector_Disk$($DiskIndex)_$timestamp.bin"
try {
# 使用 dd 類似的功能備份 MBR/GPT
$bootSectorBackup = Export-BootSector -DiskNumber $DiskIndex -OutputFile $bootBackupFile
if ($LogCallback) { & $LogCallback "開機磁區已備份: $bootBackupFile" }
}
catch {
if ($LogCallback) { & $LogCallback "警告: 無法備份開機磁區: $($_.Exception.Message)" }
}
}
if ($ProgressCallback) { & $ProgressCallback 95 }
# 驗證備份檔案
if (Test-Path $backupFilePath) {
$backupFileSize = (Get-Item $backupFilePath).Length
$backupFileSizeGB = [math]::Round($backupFileSize / 1GB, 2)
if ($LogCallback) { & $LogCallback "備份檔案大小: $backupFileSizeGB GB" }
# 使用 DISM 驗證映像完整性
$verifyArgs = @(
"/Get-ImageInfo"
"/ImageFile:`"$backupFilePath`""
)
$verifyProcess = Start-Process -FilePath $dismPath -ArgumentList $verifyArgs -Wait -PassThru -NoNewWindow -RedirectStandardOutput "$env:TEMP\dism_verify.log" -RedirectStandardError "$env:TEMP\dism_verify_error.log"
if ($verifyProcess.ExitCode -eq 0) {
if ($LogCallback) { & $LogCallback "映像檔完整性驗證通過" }
$result.Success = $true
$result.BackupFile = $backupFilePath
} else {
throw "映像檔完整性驗證失敗"
}
} else {
throw "備份檔案建立失敗"
}
if ($ProgressCallback) { & $ProgressCallback 100 }
if ($LogCallback) { & $LogCallback "系統備份完成!" }
}
catch {
$result.Error = $_.Exception.Message
if ($LogCallback) { & $LogCallback "備份失敗: $($_.Exception.Message)" }
}
return $result
}
function Export-BootSector {
param(
[int]$DiskNumber,
[string]$OutputFile
)
# 開啟磁碟進行讀取
$diskPath = "\\.\PhysicalDrive$DiskNumber"
try {
# 使用 .NET FileStream 讀取前 1MB 的資料 (包含 MBR/GPT)
$fileStream = [System.IO.FileStream]::new($diskPath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite)
$buffer = New-Object byte[] (1024 * 1024) # 1MB buffer
$bytesRead = $fileStream.Read($buffer, 0, $buffer.Length)
$fileStream.Close()
# 寫入備份檔案
[System.IO.File]::WriteAllBytes($OutputFile, $buffer)
return @{ Success = $true; BytesRead = $bytesRead }
}
catch {
throw "無法讀取磁碟開機磁區: $($_.Exception.Message)"
}
}
function Get-WindowsPartition {
param([int]$DiskNumber)
$partitions = Get-Partition -DiskNumber $DiskNumber
foreach ($partition in $partitions) {
if ($partition.DriveLetter -and (Test-Path "$($partition.DriveLetter):\Windows")) {
return $partition
}
}
return $null
}
function Test-AdminRights {
return ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
}
# 匯出函數
Export-ModuleMember -Function Start-SystemBackup, Export-BootSector, Get-WindowsPartition, Test-AdminRights