-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOneDriveMigrationScript.ps1
More file actions
881 lines (735 loc) · 31.8 KB
/
Copy pathOneDriveMigrationScript.ps1
File metadata and controls
881 lines (735 loc) · 31.8 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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
$desktopPath = [Environment]::GetFolderPath("Desktop")
$LogFile = Join-Path -Path $desktopPath -ChildPath "OneDrive_Migration.log"
$script:PollSeconds = 2
$script:HydrateTimeoutSeconds = 1800
$script:MaxPathLength = 260
Set-StrictMode -Version Latest
$script:OriginalProgressPreference = $ProgressPreference
$ProgressPreference = 'Continue'
# --- Files to skip ---
$SkipFileNames = @('desktop.ini', 'Thumbs.db', '.ds_store', '.sync', '.owncloudsync.log')
# --- Paths to exclude from migration (relative to the source folder) ---
# Preset entries, the setup asks for more. Examples: 'Archive', 'Pictures\RAW', '*\temp\*'
$ExcludePaths = @()
# ===================== Helper functions =====================
$script:ConsoleLogEnabled = $true
function Write-Log {
param(
[string]$Text,
[string]$Level = "INFO",
[switch]$ForceConsole
)
$ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$line = "[$ts] [$Level] $Text"
if ($ForceConsole -or $script:ConsoleLogEnabled -or $Level -in @("ERROR", "WARN")) {
Write-Information $line -InformationAction Continue
}
if ($LogFile) {
$logDir = Split-Path -Path $LogFile -Parent
if ($logDir -and -not (Test-Path -LiteralPath $logDir)) {
New-Item -ItemType Directory -Path $logDir -Force | Out-Null
}
$line | Out-File -FilePath $LogFile -Append -Encoding UTF8
}
}
function Update-ProgressUi {
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[int]$Index,
[int]$Total,
[string]$CurrentTask,
[string]$LastMoved
)
if (-not $PSCmdlet.ShouldProcess("Console", "Update progress UI")) { return }
$percent = 0
if ($Total -gt 0) {
$percent = [Math]::Min([Math]::Floor(($Index / $Total) * 100), 100)
}
if ([string]::IsNullOrWhiteSpace($CurrentTask)) { $CurrentTask = "Ready..." }
if ([string]::IsNullOrWhiteSpace($LastMoved)) { $LastMoved = "None yet" }
$status = "{0}% | {1}/{2} files" -f $percent, $Index, $Total
$currentOp = "{0} | Last: {1}" -f $CurrentTask, $LastMoved
Write-Progress -Activity "OneDrive Migration" -Status $status -CurrentOperation $currentOp -PercentComplete $percent
}
function Confirm-YesNo {
param(
[string]$Message,
[bool]$DefaultYes = $true
)
$hint = if ($DefaultYes) { "Y/n" } else { "y/N" }
while ($true) {
$response = Read-Input "$Message [$hint]"
if ([string]::IsNullOrWhiteSpace($response)) { return $DefaultYes }
if ($response -match '^(y|yes)$') { return $true }
if ($response -match '^(n|no)$') { return $false }
Write-Information "Please answer Y or N." -InformationAction Continue
}
}
function Read-Input {
param([string]$Prompt)
return (Read-Host $Prompt)
}
function Show-Header {
$lines = @(
"========================================",
" OneDrive Migration",
" Copy OneDrive files to Nextcloud or",
" a custom destination folder",
' All files go into "OneDriveMigration"',
" with verification and optional source dehydrate",
" Log file will be saved on your Desktop",
"========================================"
)
foreach ($line in $lines) {
Write-Information $line -InformationAction Continue
}
}
function Get-SourceDehydrateMode {
Write-Information "Dehydrate = mark file as cloud-only to free local disk space." -InformationAction Continue
Write-Information "Choose source dehydrate mode:" -InformationAction Continue
Write-Information " 1) Only files hydrated during this run (default)" -InformationAction Continue
Write-Information " 2) All source files" -InformationAction Continue
Write-Information " 3) Do not dehydrate source files" -InformationAction Continue
while ($true) {
$choice = Read-Input "Select 1, 2, or 3"
if ([string]::IsNullOrWhiteSpace($choice) -or $choice -eq "1") { return "HydratedOnly" }
if ($choice -eq "2") { return "All" }
if ($choice -eq "3") { return "None" }
Write-Information "Invalid selection." -InformationAction Continue
}
}
function Get-DestinationMode {
Write-Information "Choose destination mode:" -InformationAction Continue
Write-Information " 1) Nextcloud (default)" -InformationAction Continue
Write-Information " 2) Custom destination folder" -InformationAction Continue
while ($true) {
$choice = Read-Input "Select 1 or 2"
if ([string]::IsNullOrWhiteSpace($choice) -or $choice -eq "1") { return "Nextcloud" }
if ($choice -eq "2") { return "Custom" }
Write-Information "Invalid selection." -InformationAction Continue
}
}
function Get-CloudDestination {
$candidates = @(
[pscustomobject]@{ Name = "Nextcloud"; Path = (Get-NextcloudRoot) },
[pscustomobject]@{ Name = "Dropbox"; Path = $env:DROPBOX },
[pscustomobject]@{ Name = "Dropbox"; Path = $env:Dropbox },
[pscustomobject]@{ Name = "Google Drive"; Path = (Join-Path -Path $env:USERPROFILE -ChildPath "Google Drive") },
[pscustomobject]@{ Name = "Google Drive"; Path = (Join-Path -Path $env:USERPROFILE -ChildPath "Google Drive (Personal)") },
[pscustomobject]@{ Name = "Google Drive"; Path = (Join-Path -Path $env:USERPROFILE -ChildPath "Google Drive (Work)") },
[pscustomobject]@{ Name = "iCloud Drive"; Path = $env:ICLOUDDRIVE },
[pscustomobject]@{ Name = "iCloud Drive"; Path = (Join-Path -Path $env:USERPROFILE -ChildPath "iCloud Drive") },
[pscustomobject]@{ Name = "iCloud Drive"; Path = (Join-Path -Path $env:USERPROFILE -ChildPath "iCloudDrive") },
[pscustomobject]@{ Name = "iCloud Drive"; Path = (Join-Path -Path $env:USERPROFILE -ChildPath "iCloudDrive\iCloud Drive") },
[pscustomobject]@{ Name = "Box"; Path = (Join-Path -Path $env:USERPROFILE -ChildPath "Box") },
[pscustomobject]@{ Name = "MEGA"; Path = (Join-Path -Path $env:USERPROFILE -ChildPath "MEGA") }
)
$detected = @()
foreach ($item in $candidates) {
if (-not $item.Path) { continue }
if (Test-Path -LiteralPath $item.Path) {
$detected += $item
}
}
return ($detected | Sort-Object Name, Path -Unique)
}
function Select-DestinationRoot {
$destinations = @(Get-CloudDestination)
$options = @()
if ($destinations.Count -gt 0) {
Write-Information "Detected destination folders:" -InformationAction Continue
for ($i = 0; $i -lt $destinations.Count; $i++) {
$label = "{0} ({1})" -f $destinations[$i].Name, $destinations[$i].Path
$options += [pscustomobject]@{ Index = $i + 1; Name = $destinations[$i].Name; Path = $destinations[$i].Path; Label = $label }
Write-Information (" {0}) {1}" -f ($i + 1), $label) -InformationAction Continue
}
Write-Information (" {0}) Custom destination folder" -f ($destinations.Count + 1)) -InformationAction Continue
} else {
Write-Information "No known cloud destinations detected." -InformationAction Continue
Write-Information " 1) Custom destination folder" -InformationAction Continue
}
while ($true) {
$choice = Read-Input "Select a destination"
if ($destinations.Count -eq 0) {
if ($choice -eq "1") { return [pscustomobject]@{ Mode = "Custom"; Root = $null; Label = "Custom" } }
Write-Information "Invalid selection." -InformationAction Continue
continue
}
if ($choice -match '^\d+$') {
$idx = [int]$choice
if ($idx -ge 1 -and $idx -le $destinations.Count) {
$selected = $destinations[$idx - 1]
Write-Information "" -InformationAction Continue
return [pscustomobject]@{ Mode = $selected.Name; Root = $selected.Path; Label = $selected.Name }
}
if ($idx -eq ($destinations.Count + 1)) {
Write-Information "" -InformationAction Continue
return [pscustomobject]@{ Mode = "Custom"; Root = $null; Label = "Custom" }
}
}
Write-Information "Invalid selection." -InformationAction Continue
}
}
function Test-DehydrateSource {
param(
[string]$Mode,
[bool]$WasHydrated
)
switch ($Mode) {
"All" { return $true }
"None" { return $false }
default { return $WasHydrated }
}
}
function Get-OneDriveAccount {
$accounts = @()
$accountsKey = "HKCU:\Software\Microsoft\OneDrive\Accounts"
if (Test-Path -LiteralPath $accountsKey) {
Get-ChildItem -LiteralPath $accountsKey | ForEach-Object {
$p = Get-ItemProperty $_.PsPath -ErrorAction SilentlyContinue
if (-not $p) { return }
$userFolderProp = $p.PSObject.Properties["UserFolder"]
if (-not $userFolderProp) { return }
$accountTypeProp = $p.PSObject.Properties["AccountType"]
$accountTypeValue = if ($accountTypeProp) { $accountTypeProp.Value } else { $null }
if (-not $accountTypeValue) {
if ($_.PSChildName -match 'Business|Commercial|Enterprise' -or $userFolderProp.Value -match 'OneDrive\s-\s') {
$accountTypeValue = "Business"
} elseif ($_.PSChildName -match 'Personal|Default' -or $userFolderProp.Value -match 'OneDrive$') {
$accountTypeValue = "Personal"
}
}
$accounts += [pscustomobject]@{
Name = $_.PSChildName
UserFolder = $userFolderProp.Value
AccountType = $accountTypeValue
}
}
}
if ($accounts.Count -eq 0 -and $env:OneDrive) {
$accounts += [pscustomobject]@{
Name = "Default"
UserFolder = $env:OneDrive
AccountType = "Personal"
}
}
return $accounts
}
function Get-OneDriveAccountType {
param([object[]]$Accounts)
if ($Accounts | Where-Object { $_.AccountType -match 'Business' }) { return "Business" }
if ($Accounts | Where-Object { $_.AccountType -match 'Personal' }) { return "Personal" }
return "Unknown"
}
function Select-OneDriveFolder {
param([string[]]$Folders)
if ($Folders.Count -gt 0) {
Write-Information "Detected OneDrive folders:" -InformationAction Continue
for ($i = 0; $i -lt $Folders.Count; $i++) {
Write-Information " $($i + 1)) $($Folders[$i])" -InformationAction Continue
}
Write-Information " 2) Custom path" -InformationAction Continue
while ($true) {
$choice = Read-Input "Select folder"
if ($choice -match '[:\\/]') {
if (Test-Path -LiteralPath $choice) {
Write-Information "" -InformationAction Continue
return $choice
}
Write-Information "Path not found: $choice" -InformationAction Continue
continue
}
if ($choice -eq "2") {
$custom = Read-Input "Enter custom OneDrive path"
if (Test-Path -LiteralPath $custom) {
Write-Information "" -InformationAction Continue
return $custom
}
Write-Information "Path not found: $custom" -InformationAction Continue
continue
}
if ($choice -match '^\d+$') {
$idx = [int]$choice
if ($idx -ge 1 -and $idx -le $Folders.Count) {
$selected = $Folders[$idx - 1]
if (Confirm-YesNo -Message "Use this folder? $selected" -DefaultYes $true) {
Write-Information "" -InformationAction Continue
return $selected
}
continue
}
}
Write-Information "Invalid selection." -InformationAction Continue
}
}
while ($true) {
$custom = Read-Input "Enter OneDrive path"
if (Test-Path -LiteralPath $custom) {
Write-Information "" -InformationAction Continue
return $custom
}
Write-Information "Path not found: $custom" -InformationAction Continue
}
}
function Get-ExcludePath {
param(
[string]$SourceRoot,
[string[]]$Preset = @()
)
$patterns = [System.Collections.Generic.List[string]]::new()
foreach ($entry in $Preset) {
try {
$pattern = Resolve-ExcludePattern -Entry $entry -SourceRoot $SourceRoot
} catch {
Write-Information ("Ignoring preset exclude '{0}': {1}" -f $entry, $_.Exception.Message) -InformationAction Continue
continue
}
if ($pattern -and ($patterns -notcontains $pattern)) { $patterns.Add($pattern) }
}
Write-Information "Exclude paths are not migrated and stay untouched (no hydrate, no dehydrate)." -InformationAction Continue
Write-Information " Enter a path relative to the source folder, or an absolute path inside it." -InformationAction Continue
Write-Information " Wildcards are allowed, e.g. Archive\* or *\temp\*" -InformationAction Continue
Write-Information " Leave empty and press Enter when done." -InformationAction Continue
if ($patterns.Count -gt 0) {
Write-Information "Preset excludes:" -InformationAction Continue
foreach ($p in $patterns) { Write-Information " - $p" -InformationAction Continue }
}
while ($true) {
$entry = Read-Input "Exclude path (empty = done)"
if ([string]::IsNullOrWhiteSpace($entry)) { break }
try {
$pattern = Resolve-ExcludePattern -Entry $entry -SourceRoot $SourceRoot
} catch {
Write-Information $_.Exception.Message -InformationAction Continue
continue
}
if (-not $pattern) { continue }
if ($patterns -contains $pattern) {
Write-Information "Already on the list: $pattern" -InformationAction Continue
continue
}
# Typo guard - only meaningful without wildcards
if ($pattern -notmatch '[*?]') {
$probe = Join-Path -Path $SourceRoot -ChildPath $pattern
if (-not (Test-Path -LiteralPath $probe)) {
if (-not (Confirm-YesNo -Message "Not found in source: $pattern. Add anyway?" -DefaultYes $false)) {
continue
}
}
}
$patterns.Add($pattern)
Write-Information "Excluded: $pattern" -InformationAction Continue
}
if ($patterns.Count -eq 0) {
Write-Information "No exclude paths - migrating everything." -InformationAction Continue
} else {
Write-Information "Exclude list:" -InformationAction Continue
foreach ($p in $patterns) { Write-Information " - $p" -InformationAction Continue }
}
return ,$patterns.ToArray()
}
function Get-NextcloudRoot {
$candidates = @()
if ($env:NEXTCLOUD) { $candidates += $env:NEXTCLOUD }
if ($env:Nextcloud) { $candidates += $env:Nextcloud }
if ($env:USERPROFILE) { $candidates += (Join-Path -Path $env:USERPROFILE -ChildPath "Nextcloud") }
$candidates = $candidates | Where-Object { $_ } | Select-Object -Unique
foreach ($path in $candidates) {
if (Test-Path -LiteralPath $path) { return $path }
}
return $null
}
function New-FolderIfMissing {
[CmdletBinding(SupportsShouldProcess = $true)]
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path)) {
if ($PSCmdlet.ShouldProcess($Path, "Create directory")) {
New-Item -ItemType Directory -Path $Path -Force | Out-Null
}
}
}
function Test-CloudOnly {
param([string]$Path)
try {
$item = Get-Item -LiteralPath $Path -Force -ErrorAction Stop
# Offline attribute = file is cloud-only (not stored locally)
return (($item.Attributes -band [IO.FileAttributes]::Offline) -ne 0)
} catch {
Write-Log "Attribute check failed: $Path | $_" -Level "WARN"
return $false
}
}
function Test-PathTooLong {
param(
[string]$Path,
[int]$MaxLength = $script:MaxPathLength
)
if ([string]::IsNullOrEmpty($Path)) { return $false }
return ($Path.Length -ge $MaxLength)
}
function Invoke-HydrateFile {
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path)) {
throw "File not found: $Path"
}
if (-not (Test-CloudOnly -Path $Path)) {
return $false
}
# Set pin attribute -> OneDrive downloads the file
$attribOut = & attrib.exe +P -U "$Path" 2>&1
if ($LASTEXITCODE -ne 0) {
throw "attrib +P -U failed ($LASTEXITCODE): $attribOut"
}
$sw = [Diagnostics.Stopwatch]::StartNew()
$lastErr = $null
# Progressive polling: check fast first (200ms), then slow down
# Avoids unnecessary waiting for small files
$currentWaitMs = 200
while ($true) {
# Try to read the file - only when this works is it actually local
try {
$fs = [System.IO.File]::Open(
$Path,
[System.IO.FileMode]::Open,
[System.IO.FileAccess]::Read,
[System.IO.FileShare]::ReadWrite
)
try {
$buf = New-Object byte[] 1
[void]$fs.Read($buf, 0, 1)
} finally {
$fs.Close()
$fs.Dispose()
}
} catch {
$lastErr = $_.Exception.Message
}
if (-not (Test-CloudOnly -Path $Path)) { break }
if ($sw.Elapsed.TotalSeconds -ge $script:HydrateTimeoutSeconds) {
$msg = "Hydrate timeout ($script:HydrateTimeoutSeconds s): $Path"
if ($lastErr) { $msg += " | LastError: $lastErr" }
throw $msg
}
Start-Sleep -Milliseconds $currentWaitMs
# Increase progressively: 200ms -> 400ms -> 800ms -> 1600ms -> max 2000ms
$currentWaitMs = [Math]::Min($currentWaitMs * 2, $script:PollSeconds * 1000)
}
return $true
}
function Invoke-DehydrateFile {
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path)) { return }
if (Test-CloudOnly -Path $Path) {
return
}
$attribOut = & attrib.exe -P +U "$Path" 2>&1
if ($LASTEXITCODE -ne 0) {
Write-Log "attrib -P +U failed ($LASTEXITCODE): $attribOut | $Path" -Level "WARN"
# No throw - not critical, file stays local
}
}
function Get-RelativePathSafe {
param([string]$Root, [string]$FullPath)
$rootNorm = [System.IO.Path]::GetFullPath($Root).TrimEnd('\') + '\'
$fullNorm = [System.IO.Path]::GetFullPath($FullPath)
if (-not $fullNorm.StartsWith($rootNorm, [System.StringComparison]::OrdinalIgnoreCase)) {
throw "Path is not under root. Root=$Root | Path=$FullPath"
}
return $fullNorm.Substring($rootNorm.Length)
}
function Resolve-ExcludePattern {
param(
[string]$Entry,
[string]$SourceRoot
)
if ([string]::IsNullOrWhiteSpace($Entry)) { return $null }
$pattern = $Entry.Trim().Trim('"').Trim("'").Trim()
$pattern = $pattern.Replace('/', '\').TrimEnd('\')
if ([string]::IsNullOrWhiteSpace($pattern)) { return $null }
# Absolute input is only useful if it points inside the source folder.
# Note: no GetFullPath here - it chokes on wildcards in Windows PowerShell.
if ($pattern -match '^[A-Za-z]:\\' -or $pattern.StartsWith('\\')) {
$rootNorm = [System.IO.Path]::GetFullPath($SourceRoot).TrimEnd('\')
if ($pattern.Equals($rootNorm, [System.StringComparison]::OrdinalIgnoreCase)) {
throw "That is the source folder itself - nothing would be migrated: $Entry"
}
if (-not $pattern.StartsWith($rootNorm + '\', [System.StringComparison]::OrdinalIgnoreCase)) {
throw "Absolute path is not inside the source folder: $Entry"
}
$pattern = $pattern.Substring($rootNorm.Length + 1)
if ([string]::IsNullOrWhiteSpace($pattern)) { return $null }
}
return $pattern
}
function Test-PathExcluded {
param(
[string]$RelativePath,
[string[]]$Patterns
)
if (-not $Patterns -or $Patterns.Count -eq 0) { return $false }
foreach ($pattern in $Patterns) {
if ([string]::IsNullOrWhiteSpace($pattern)) { continue }
if ($pattern -match '[*?]') {
# -like is case-insensitive and * spans backslashes, so Archive\* covers the whole subtree
if ($RelativePath -like $pattern) { return $true }
continue
}
# Exact match = single file, prefix match = whole folder
if ($RelativePath.Equals($pattern, [System.StringComparison]::OrdinalIgnoreCase)) { return $true }
if ($RelativePath.StartsWith($pattern + '\', [System.StringComparison]::OrdinalIgnoreCase)) { return $true }
}
return $false
}
function Copy-FileStreaming {
param([string]$Src, [string]$Dst)
$srcStream = $null
$dstStream = $null
try {
$srcStream = [System.IO.File]::Open(
$Src,
[System.IO.FileMode]::Open,
[System.IO.FileAccess]::Read,
[System.IO.FileShare]::ReadWrite
)
$dstStream = [System.IO.File]::Open(
$Dst,
[System.IO.FileMode]::Create,
[System.IO.FileAccess]::Write,
[System.IO.FileShare]::None
)
$buffer = New-Object byte[] (4MB)
while ($true) {
$read = $srcStream.Read($buffer, 0, $buffer.Length)
if ($read -le 0) { break }
$dstStream.Write($buffer, 0, $read)
}
$dstStream.Flush()
} finally {
if ($dstStream) { $dstStream.Close(); $dstStream.Dispose() }
if ($srcStream) { $srcStream.Close(); $srcStream.Dispose() }
}
}
function Test-Copy {
param([string]$Src, [string]$Dst)
if (-not (Test-Path -LiteralPath $Dst)) {
throw "Destination file does not exist after copy: $Dst"
}
$srcSize = (Get-Item -LiteralPath $Src -Force).Length
$dstSize = (Get-Item -LiteralPath $Dst -Force).Length
if ($srcSize -ne $dstSize) {
# Delete destination so no corrupt file remains
Remove-Item -LiteralPath $Dst -Force -ErrorAction SilentlyContinue
throw "Size check failed! Src=$srcSize Dst=$dstSize | $Dst"
}
}
# ===================== Interactive setup =====================
Show-Header
$accounts = Get-OneDriveAccount
$detectedType = Get-OneDriveAccountType -Accounts $accounts
if ($detectedType -eq "Unknown") {
Write-Information "Detected OneDrive account type: Unknown" -InformationAction Continue
Write-Information "Defaulting to Personal (can be changed below)." -InformationAction Continue
$detectedType = "Personal"
} else {
Write-Information "Detected OneDrive account type: $detectedType" -InformationAction Continue
}
if (-not (Confirm-YesNo -Message "Is this correct?" -DefaultYes $true)) {
$typed = Read-Input "Enter account type (P=Personal, B=Business)"
if ($typed -match '^[bB]') { $detectedType = "Business" } else { $detectedType = "Personal" }
}
Write-Information ("Using account type: {0}" -f $detectedType) -InformationAction Continue
Write-Information "" -InformationAction Continue
$oneDriveFolders = @($accounts | Where-Object { $_.UserFolder } | Select-Object -ExpandProperty UserFolder -Unique)
if ($detectedType -eq "Business" -and $oneDriveFolders.Count -gt 1) {
Write-Information "Multiple business OneDrive folders detected." -InformationAction Continue
}
$SourceRoot = Select-OneDriveFolder -Folders $oneDriveFolders
$ExcludePatterns = @(Get-ExcludePath -SourceRoot $SourceRoot -Preset $ExcludePaths)
Write-Information "" -InformationAction Continue
$sourceDehydrateMode = Get-SourceDehydrateMode
Write-Information ("Source dehydrate mode: {0}" -f $sourceDehydrateMode) -InformationAction Continue
Write-Information "" -InformationAction Continue
$destinationChoice = Select-DestinationRoot
Write-Information ("Destination mode: {0}" -f $destinationChoice.Label) -InformationAction Continue
Write-Information "" -InformationAction Continue
if ($destinationChoice.Mode -ne "Custom") {
$DestRoot = Join-Path -Path $destinationChoice.Root -ChildPath "OneDriveMigration"
New-FolderIfMissing -Path $DestRoot
} else {
while ($true) {
$customDest = Read-Input "Enter destination folder"
if (Test-Path -LiteralPath $customDest) {
$DestRoot = $customDest
Write-Information "" -InformationAction Continue
break
}
if (Confirm-YesNo -Message "Path not found. Create it?" -DefaultYes $false) {
New-FolderIfMissing -Path $customDest
$DestRoot = $customDest
break
}
}
}
# ===================== Main program =====================
try {
if (-not (Test-Path -LiteralPath $SourceRoot)) {
throw "SourceRoot does not exist: $SourceRoot"
}
if (-not (Test-Path -LiteralPath $DestRoot)) {
Write-Log "DestRoot does not exist, creating: $DestRoot"
New-Item -ItemType Directory -Path $DestRoot -Force | Out-Null
}
Write-Log "=========================================="
Write-Log "Migration started"
Write-Log "Source: $SourceRoot"
Write-Log "Dest: $DestRoot"
Write-Log "LogFile: $LogFile"
if ($ExcludePatterns.Count -gt 0) {
Write-Log "Excluded paths:"
foreach ($pattern in $ExcludePatterns) {
Write-Log " $pattern"
}
}
Write-Log "=========================================="
$script:ConsoleLogEnabled = $false
# List files (metadata only, no download)
# @() ensures we always get an array (even for 0 or 1 file)
[array]$candidates = @(Get-ChildItem -LiteralPath $SourceRoot -File -Recurse -Force |
Where-Object { $SkipFileNames -notcontains $_.Name })
# Drop excluded paths before anything touches them - they stay hydrated/dehydrated as they are
$excludedCount = 0
$kept = [System.Collections.Generic.List[object]]::new()
foreach ($candidate in $candidates) {
if ($ExcludePatterns.Count -gt 0) {
$relCandidate = $null
try {
$relCandidate = Get-RelativePathSafe -Root $SourceRoot -FullPath $candidate.FullName
} catch {
Write-Log "Exclude check skipped (relative path failed): $($candidate.FullName) | $_" -Level "WARN"
}
if ($relCandidate -and (Test-PathExcluded -RelativePath $relCandidate -Patterns $ExcludePatterns)) {
$excludedCount++
Write-Log "Excluded: $relCandidate"
continue
}
}
$kept.Add($candidate)
}
[array]$files = @($kept | Sort-Object -Property Length, FullName)
$total = $files.Count
$index = 0
$okCount = 0
$skipCount = 0
$errCount = 0
$errList = @()
$currentTask = ""
$lastMoved = ""
Write-Log "Found files: $total (after filter, $excludedCount excluded by path)"
Update-ProgressUi -Index 0 -Total $total -CurrentTask "Initializing" -LastMoved $lastMoved
foreach ($file in $files) {
$index++
$src = $file.FullName
$rel = Get-RelativePathSafe -Root $SourceRoot -FullPath $src
$dst = Join-Path -Path $DestRoot -ChildPath $rel
$dstDir = Split-Path -Path $dst -Parent
$wasHydrated = $false
if ((Test-PathTooLong -Path $src) -or (Test-PathTooLong -Path $dst)) {
$errCount++
$errMsg = "ERROR at [$index/$total] $rel : Path too long (max $script:MaxPathLength). Skipped."
$errList += $errMsg
Write-Log $errMsg -Level "ERROR"
$currentTask = "Error (path too long)"
Update-ProgressUi -Index $index -Total $total -CurrentTask $currentTask -LastMoved $lastMoved
continue
}
$currentTask = "Checking file: $rel"
Update-ProgressUi -Index $index -Total $total -CurrentTask $currentTask -LastMoved $lastMoved
# Already copied? Compare size (resume support)
if (Test-Path -LiteralPath $dst) {
$existingSize = (Get-Item -LiteralPath $dst -Force).Length
$sourceSize = $file.Length
if ($existingSize -eq $sourceSize -and $sourceSize -gt 0) {
# Dehydrate source if still local
$currentTask = "Skipped (already exists)"
Update-ProgressUi -Index $index -Total $total -CurrentTask $currentTask -LastMoved $lastMoved
if (Test-DehydrateSource -Mode $sourceDehydrateMode -WasHydrated $wasHydrated) {
Invoke-DehydrateFile -Path $src
}
$skipCount++
continue
}
}
try {
# 1. Download file (hydrate)
$currentTask = "Hydrate (download)"
Update-ProgressUi -Index $index -Total $total -CurrentTask $currentTask -LastMoved $lastMoved
$wasHydrated = Invoke-HydrateFile -Path $src
# 2. Ensure destination folder
$currentTask = "Ensure destination folder"
Update-ProgressUi -Index $index -Total $total -CurrentTask $currentTask -LastMoved $lastMoved
New-FolderIfMissing -Path $dstDir
# 3. Copy file
$currentTask = "Copying file"
Update-ProgressUi -Index $index -Total $total -CurrentTask $currentTask -LastMoved $lastMoved
Copy-FileStreaming -Src $src -Dst $dst
# 4. Verify copy (size check)
$currentTask = "Verifying copy"
Update-ProgressUi -Index $index -Total $total -CurrentTask $currentTask -LastMoved $lastMoved
Test-Copy -Src $src -Dst $dst
# 5. Dehydrate source (free space on OneDrive)
$currentTask = "Free space (Source)"
Update-ProgressUi -Index $index -Total $total -CurrentTask $currentTask -LastMoved $lastMoved
if (Test-DehydrateSource -Mode $sourceDehydrateMode -WasHydrated $wasHydrated) {
Invoke-DehydrateFile -Path $src
}
Write-Log "Completed: $rel"
$okCount++
$lastMoved = $rel
$currentTask = "Done"
Update-ProgressUi -Index $index -Total $total -CurrentTask $currentTask -LastMoved $lastMoved
} catch {
$errCount++
$errMsg = "ERROR at [$index/$total] $rel : $($_.Exception.Message)"
$errList += $errMsg
Write-Log $errMsg -Level "ERROR"
$currentTask = "Error (see log)"
Update-ProgressUi -Index $index -Total $total -CurrentTask $currentTask -LastMoved $lastMoved
# Dehydrate source if it was hydrated
try {
if (Test-DehydrateSource -Mode $sourceDehydrateMode -WasHydrated $wasHydrated) {
Invoke-DehydrateFile -Path $src
}
} catch {
Write-Log "Cleanup dehydrate failed: $src | $_" -Level "WARN"
}
# Delete faulty destination file
if (Test-Path -LiteralPath $dst) {
Remove-Item -LiteralPath $dst -Force -ErrorAction SilentlyContinue
}
# Continue with next file instead of aborting
continue
}
}
$script:ConsoleLogEnabled = $true
# ===================== Summary =====================
Write-Log "=========================================="
Write-Log "Migration completed"
Write-Log "Total: $total"
Write-Log "Successful: $okCount"
Write-Log "Skipped: $skipCount"
Write-Log "Excluded: $excludedCount"
Write-Log "Errors: $errCount"
Write-Log "=========================================="
if ($errList.Count -gt 0) {
Write-Log "Error list:" -Level "ERROR"
foreach ($e in $errList) {
Write-Log " $e" -Level "ERROR"
}
}
Write-Log "LogFile: $LogFile"
} finally {
$script:ConsoleLogEnabled = $true
$ProgressPreference = $script:OriginalProgressPreference
Write-Information "" -InformationAction Continue
[void](Read-Input "Press Enter to close this script...")
}