-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloud_module.ps1
More file actions
511 lines (421 loc) · 16.4 KB
/
cloud_module.ps1
File metadata and controls
511 lines (421 loc) · 16.4 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
<#
CloudModule.ps1 - OneDrive 上傳模組
Version: v0.2
歷史版本:
v0.1 - 初始版本,實現基本的OneDrive同步功能
v0.2 - 增加詳細日誌記錄,改進錯誤處理機制
#>
<#
.SYNOPSIS
提供與OneDrive同步相關的各種功能,包括上傳、下載、文件列表查詢等
.DESCRIPTION
此模組封裝了與OneDrive本地同步文件夾交互的各種操作,
依賴OneDrive桌面客戶端進行後台同步,支持進度跟蹤和錯誤處理
#>
function Upload-ToOneDrive {
<#
.SYNOPSIS
上傳本地文件到OneDrive
.PARAMETER FilePath
本地文件路徑
.PARAMETER RemotePath
OneDrive上的目標路徑,預設為"/SystemBackups/"
.PARAMETER ProgressCallback
進度回調函數,用於報告上傳進度
.RETURNS
包含操作結果的哈希表,包含Success、OneDriveUrl、Error和UploadedSize字段
#>
param(
[string]$FilePath,
[string]$RemotePath = "/SystemBackups/",
[scriptblock]$ProgressCallback = $null
)
$result = @{
Success = $false
OneDriveUrl = $null
Error = $null
UploadedSize = 0
}
try {
# 檢查檔案是否存在
if (-not (Test-Path $FilePath)) {
throw "檔案不存在: $FilePath"
}
$fileInfo = Get-Item $FilePath
$fileName = $fileInfo.Name
$fileSize = $fileInfo.Length
$fileSizeMB = [math]::Round($fileSize / 1MB, 2)
Add-LogEntry -Message "準備上傳檔案到 OneDrive: $fileName ($fileSizeMB MB)" -ForegroundColor Green
Write-Host "準備上傳檔案到 OneDrive: $fileName ($fileSizeMB MB)" -ForegroundColor Green
# 檢查 OneDrive 是否已安裝和登入
$oneDriveStatus = Test-OneDriveConnection
if (-not $oneDriveStatus.Success) {
throw $oneDriveStatus.Error
}
# 獲取 OneDrive 本地同步資料夾路徑
$oneDriveLocalPath = Get-OneDriveLocalPath
if (-not $oneDriveLocalPath) {
throw "無法找到 OneDrive 本地同步資料夾"
}
Add-LogEntry -Message "OneDrive 本地路徑: $oneDriveLocalPath" -ForegroundColor Yellow
Write-Host "OneDrive 本地路徑: $oneDriveLocalPath" -ForegroundColor Yellow
# 建立遠端目錄結構
$targetDir = Join-Path $oneDriveLocalPath $RemotePath.TrimStart('/')
if (-not (Test-Path $targetDir)) {
New-Item -Path $targetDir -ItemType Directory -Force | Out-Null
Add-LogEntry -Message "建立目錄: $targetDir" -ForegroundColor Cyan
}
# 建立目標檔案路徑
$targetFilePath = Join-Path $targetDir $fileName
# 檢查目標檔案是否已存在
if (Test-Path $targetFilePath) {
$overwriteChoice = Read-Host "檔案 $fileName 已存在於 OneDrive,是否覆蓋?(Y/N)"
if ($overwriteChoice -ne 'Y' -and $overwriteChoice -ne 'y') {
throw "使用者取消上傳"
}
}
# 開始複製檔案到 OneDrive 本地同步資料夾
Add-LogEntry -Message "開始複製檔案到 OneDrive 同步資料夾..." -ForegroundColor Yellow
Write-Host "開始複製檔案到 OneDrive 同步資料夾..." -ForegroundColor Yellow
if ($ProgressCallback) {
# 使用帶進度回報的複製方法
Copy-FileWithProgress -SourcePath $FilePath -DestinationPath $targetFilePath -ProgressCallback $ProgressCallback
} else {
# 直接複製
Copy-Item -Path $FilePath -Destination $targetFilePath -Force
}
Add-LogEntry -Message "檔案已複製到 OneDrive 同步資料夾" -ForegroundColor Green
Write-Host "檔案已複製到 OneDrive 同步資料夾" -ForegroundColor Green
# 等待 OneDrive 同步完成
Add-LogEntry -Message "等待 OneDrive 同步..." -ForegroundColor Yellow
Write-Host "等待 OneDrive 同步..." -ForegroundColor Yellow
$syncResult = Wait-OneDriveSync -FilePath $targetFilePath -TimeoutMinutes 30
if ($syncResult.Success) {
Add-LogEntry -Message "OneDrive 同步完成" -ForegroundColor Green
$result.Success = $true
$result.UploadedSize = $fileSize
$result.OneDriveUrl = "https://onedrive.live.com" # 簡化的 URL
} else {
throw "OneDrive 同步失敗或超時: $($syncResult.Error)"
}
}
catch {
$result.Error = $_.Exception.Message
Add-LogEntry -Message "OneDrive 上傳失敗: $($_.Exception.Message)" -ForegroundColor Red
Write-Host "OneDrive 上傳失敗: $($_.Exception.Message)" -ForegroundColor Red
}
return $result
}
function Test-OneDriveConnection {
<#
.SYNOPSIS
檢查OneDrive客戶端是否已連接並且可用
.RETURNS
包含操作結果的哈希表,包含Success、Error和Version字段
#>
$result = @{
Success = $false
Error = $null
Version = $null
}
try {
# 檢查 OneDrive 程序是否在執行
$oneDriveProcess = Get-Process -Name "OneDrive" -ErrorAction SilentlyContinue
if (-not $oneDriveProcess) {
$result.Error = "OneDrive 未在執行,請先啟動 OneDrive 並登入"
Add-LogEntry -Message $result.Error -Level WARNING
return $result
}
# 檢查登入狀態 (透過檢查設定檔案)
$oneDriveSettingsPath = "$env:LOCALAPPDATA\Microsoft\OneDrive\settings"
if (-not (Test-Path $oneDriveSettingsPath)) {
$result.Error = "OneDrive 未正確設定或未登入"
Add-LogEntry -Message $result.Error -Level WARNING
return $result
}
$result.Success = $true
$result.Version = $oneDriveProcess.FileVersion
Add-LogEntry -Message "OneDrive 連接正常,版本: $($result.Version)" -Level INFO
}
catch {
$result.Error = $_.Exception.Message
Add-LogEntry -Message "檢查OneDrive連接失敗: $($_.Exception.Message)" -Level ERROR
}
return $result
}
function Get-OneDriveLocalPath {
try {
# 方法1: 從註冊表獲取
$regPath = "HKCU:\Software\Microsoft\OneDrive"
if (Test-Path $regPath) {
$oneDrivePath = (Get-ItemProperty -Path $regPath -Name "UserFolder" -ErrorAction SilentlyContinue).UserFolder
if ($oneDrivePath -and (Test-Path $oneDrivePath)) {
return $oneDrivePath
}
}
# 方法2: 檢查預設位置
$defaultPaths = @(
"$env:USERPROFILE\OneDrive",
"$env:USERPROFILE\OneDrive - Personal",
"$env:OneDrive"
)
foreach ($path in $defaultPaths) {
if ($path -and (Test-Path $path)) {
return $path
}
}
# 方法3: 搜尋常見位置
$commonPaths = Get-ChildItem -Path $env:USERPROFILE -Directory -Filter "*OneDrive*" -ErrorAction SilentlyContinue
if ($commonPaths) {
return $commonPaths[0].FullName
}
return $null
}
catch {
return $null
}
}
function Copy-FileWithProgress {
param(
[string]$SourcePath,
[string]$DestinationPath,
[scriptblock]$ProgressCallback
)
try {
$sourceFile = Get-Item $SourcePath
$totalSize = $sourceFile.Length
$bufferSize = 1MB
$copiedBytes = 0
$sourceStream = [System.IO.File]::OpenRead($SourcePath)
$destinationStream = [System.IO.File]::Create($DestinationPath)
$buffer = New-Object byte[] $bufferSize
try {
while ($copiedBytes -lt $totalSize) {
$remainingBytes = $totalSize - $copiedBytes
$bytesToRead = [Math]::Min($bufferSize, $remainingBytes)
$bytesRead = $sourceStream.Read($buffer, 0, $bytesToRead)
if ($bytesRead -eq 0) { break }
$destinationStream.Write($buffer, 0, $bytesRead)
$copiedBytes += $bytesRead
# 計算進度百分比
$progressPercent = [Math]::Round(($copiedBytes / $totalSize) * 100, 1)
if ($ProgressCallback) {
& $ProgressCallback $progressPercent
}
# 每複製 10MB 顯示一次進度
if ($copiedBytes % (10MB) -eq 0 -or $copiedBytes -eq $totalSize) {
$copiedMB = [Math]::Round($copiedBytes / 1MB, 1)
$totalMB = [Math]::Round($totalSize / 1MB, 1)
Add-LogEntry -Message "已複製: $copiedMB MB / $totalMB MB ($progressPercent%)" -ForegroundColor Cyan
Write-Host "已複製: $copiedMB MB / $totalMB MB ($progressPercent%)" -ForegroundColor Cyan
}
}
}
finally {
$sourceStream.Close()
$destinationStream.Close()
}
if ($copiedBytes -eq $totalSize) {
Add-LogEntry -Message "檔案複製完成" -ForegroundColor Green
Write-Host "檔案複製完成" -ForegroundColor Green
} else {
throw "檔案複製未完成,只複製了 $copiedBytes / $totalSize 位元組"
}
}
catch {
# 清理不完整的目標檔案
if (Test-Path $DestinationPath) {
Remove-Item $DestinationPath -Force -ErrorAction SilentlyContinue
}
throw
}
}
function Wait-OneDriveSync {
param(
[string]$FilePath,
[int]$TimeoutMinutes = 30
)
$result = @{
Success = $false
Error = $null
}
try {
$timeout = (Get-Date).AddMinutes($TimeoutMinutes)
$checkIntervalSeconds = 10
Add-LogEntry -Message "監控 OneDrive 同步狀態..." -ForegroundColor Yellow
Write-Host "監控 OneDrive 同步狀態..." -ForegroundColor Yellow
while ((Get-Date) -lt $timeout) {
# 檢查檔案同步狀態
$syncStatus = Get-OneDriveFileSyncStatus -FilePath $FilePath
switch ($syncStatus) {
"Synced" {
$result.Success = $true
return $result
}
"Syncing" {
Add-LogEntry -Message "同步中..." -ForegroundColor Cyan
Write-Host "同步中..." -ForegroundColor Cyan
}
"Error" {
$result.Error = "同步過程中發生錯誤"
return $result
}
"NotFound" {
$result.Error = "檔案未找到或未開始同步"
return $result
}
default {
Add-LogEntry -Message "同步狀態: $syncStatus" -ForegroundColor Yellow
Write-Host "同步狀態: $syncStatus" -ForegroundColor Yellow
}
}
Start-Sleep -Seconds $checkIntervalSeconds
}
$result.Error = "同步超時 ($TimeoutMinutes 分鐘)"
}
catch {
$result.Error = $_.Exception.Message
Add-LogEntry -Message "OneDrive 上傳失敗: $($_.Exception.Message)" -Level ERROR -ConsoleOutput
Write-Host "OneDrive 上傳失敗: $($_.Exception.Message)" -Level ERROR -ConsoleOutput
}
return $result
}
function Get-OneDriveFileSyncStatus {
param([string]$FilePath)
try {
if (-not (Test-Path $FilePath)) {
return "NotFound"
}
# 檢查檔案屬性中的 OneDrive 同步狀態
# 這是簡化的實作,實際情況可能需要更複雜的 API 呼叫
# 方法1: 檢查檔案是否有 OneDrive 特殊屬性
$fileAttributes = (Get-Item $FilePath).Attributes
# 方法2: 檢查 OneDrive 狀態圖示 (透過 Shell API)
# 這裡簡化處理,假設檔案存在就是已同步
# 檢查檔案大小是否穩定 (簡單的同步檢測)
$initialSize = (Get-Item $FilePath).Length
Start-Sleep -Seconds 2
$currentSize = (Get-Item $FilePath).Length
if ($initialSize -eq $currentSize -and $currentSize -gt 0) {
return "Synced"
} else {
return "Syncing"
}
}
catch {
return "Error"
}
}
function Download-FromOneDrive {
param(
[string]$RemotePath,
[string]$LocalPath,
[scriptblock]$ProgressCallback = $null
)
$result = @{
Success = $false
LocalFile = $null
Error = $null
}
try {
# 獲取 OneDrive 本地同步路徑
$oneDriveLocalPath = Get-OneDriveLocalPath
if (-not $oneDriveLocalPath) {
throw "無法找到 OneDrive 本地同步資料夾"
}
# 建立來源檔案路徑
$sourceFilePath = Join-Path $oneDriveLocalPath $RemotePath.TrimStart('/')
if (-not (Test-Path $sourceFilePath)) {
throw "OneDrive 中找不到檔案: $RemotePath"
}
Add-LogEntry -Message "從 OneDrive 下載檔案: $RemotePath" -ForegroundColor Green
Write-Host "從 OneDrive 下載檔案: $RemotePath" -ForegroundColor Green
# 確保本地目錄存在
$localDir = [System.IO.Path]::GetDirectoryName($LocalPath)
if (-not (Test-Path $localDir)) {
New-Item -Path $localDir -ItemType Directory -Force | Out-Null
}
# 複製檔案
if ($ProgressCallback) {
Copy-FileWithProgress -SourcePath $sourceFilePath -DestinationPath $LocalPath -ProgressCallback $ProgressCallback
} else {
Copy-Item -Path $sourceFilePath -Destination $LocalPath -Force
}
$result.Success = $true
$result.LocalFile = $LocalPath
Add-LogEntry -Message "下載完成: $LocalPath" -ForegroundColor Green
Write-Host "下載完成: $LocalPath" -ForegroundColor Green
}
catch {
$result.Error = $_.Exception.Message
Add-LogEntry -Message "OneDrive 下載失敗: $($_.Exception.Message)" -ForegroundColor Red
Write-Host "OneDrive 下載失敗: $($_.Exception.Message)" -ForegroundColor Red
}
return $result
}
function Get-OneDriveFileList {
param([string]$RemotePath = "/")
$result = @{
Success = $false
Files = @()
Error = $null
}
try {
# 獲取 OneDrive 本地同步路徑
$oneDriveLocalPath = Get-OneDriveLocalPath
if (-not $oneDriveLocalPath) {
throw "無法找到 OneDrive 本地同步資料夾"
}
# 建立搜尋路徑
$searchPath = Join-Path $oneDriveLocalPath $RemotePath.TrimStart('/')
if (Test-Path $searchPath) {
$files = Get-ChildItem -Path $searchPath -Recurse -File | ForEach-Object {
@{
Name = $_.Name
FullName = $_.FullName
Size = $_.Length
LastModified = $_.LastWriteTime
RelativePath = $_.FullName.Substring($oneDriveLocalPath.Length).Replace('\', '/')
}
}
$result.Files = $files
$result.Success = $true
} else {
$result.Error = "路徑不存在: $RemotePath"
}
}
catch {
$result.Error = $_.Exception.Message
}
return $result
}
function Remove-OneDriveFile {
param([string]$RemotePath)
$result = @{
Success = $false
Error = $null
}
try {
# 獲取 OneDrive 本地同步路徑
$oneDriveLocalPath = Get-OneDriveLocalPath
if (-not $oneDriveLocalPath) {
throw "無法找到 OneDrive 本地同步資料夾"
}
# 建立檔案路徑
$filePath = Join-Path $oneDriveLocalPath $RemotePath.TrimStart('/')
if (Test-Path $filePath) {
Remove-Item -Path $filePath -Force
Add-LogEntry -Message "已刪除 OneDrive 檔案: $RemotePath" -ForegroundColor Yellow
Write-Host "已刪除 OneDrive 檔案: $RemotePath" -ForegroundColor Yellow
$result.Success = $true
} else {
$result.Error = "檔案不存在: $RemotePath"
}
}
catch {
$result.Error = $_.Exception.Message
}
return $result
}
# 匯出函數
Export-ModuleMember -Function Upload-ToOneDrive, Download-FromOneDrive, Test-OneDriveConnection, Get-OneDriveLocalPath, Get-OneDriveFileList, Remove-OneDriveFile