-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopy-GraphMailboxItems.ps1
More file actions
2465 lines (1981 loc) · 82.1 KB
/
Copy pathCopy-GraphMailboxItems.ps1
File metadata and controls
2465 lines (1981 loc) · 82.1 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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[string]$SourceUserPrincipalName,
[string]$TargetUserPrincipalName,
[string]$SourceFolderPath,
[string]$TargetFolderPath = '',
[string]$SourceTenantId,
[string]$SourceClientId,
[string]$SourceCertificateThumbprint,
[string]$TargetTenantId,
[string]$TargetClientId,
[string]$TargetCertificateThumbprint,
[string]$TenantId,
[string]$ClientId,
[string]$CertificateThumbprint,
[switch]$ImportDirectlyIntoTargetFolder,
[switch]$OverlayMode,
[switch]$CopyEmptyFolders,
[string[]]$IncludeFolderPath,
[string[]]$ExcludeFolderPath,
[string]$Oldest,
[string]$Newest,
[switch]$PreflightOnly,
[switch]$Force,
[string]$EnvFile = '.env',
[int]$ExportBatchSize = 20
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$script:RootParentKey = '__root__'
$script:AlwaysExcludedFolderDisplayNames = @(
'Conversation History',
'Journal',
'RSS Subscriptions'
)
$script:AlwaysExcludedFolderTypes = @(
'IPF.Journal'
)
function ConvertFrom-DotEnvValue {
param(
[AllowNull()]
[string]$Value
)
if ($null -eq $Value) {
return ''
}
$trimmedValue = $Value.Trim()
if ($trimmedValue.Length -ge 2) {
$firstCharacter = $trimmedValue.Substring(0, 1)
$lastCharacter = $trimmedValue.Substring($trimmedValue.Length - 1, 1)
if (($firstCharacter -eq '"' -and $lastCharacter -eq '"') -or ($firstCharacter -eq "'" -and $lastCharacter -eq "'")) {
return $trimmedValue.Substring(1, $trimmedValue.Length - 2)
}
}
return $trimmedValue
}
function Read-DotEnvFile {
param(
[Parameter(Mandatory = $true)]
[string]$Path
)
$resolvedPath = Resolve-Path -LiteralPath $Path -ErrorAction Stop
$values = @{}
foreach ($line in (Get-Content -LiteralPath $resolvedPath)) {
$trimmedLine = $line.Trim()
if ([string]::IsNullOrWhiteSpace($trimmedLine) -or $trimmedLine.StartsWith('#')) {
continue
}
$separatorIndex = $trimmedLine.IndexOf('=')
if ($separatorIndex -lt 1) {
continue
}
$key = $trimmedLine.Substring(0, $separatorIndex).Trim()
$value = $trimmedLine.Substring($separatorIndex + 1)
if ($key.StartsWith('export ')) {
$key = $key.Substring(7).Trim()
}
if (-not [string]::IsNullOrWhiteSpace($key)) {
$values[$key] = ConvertFrom-DotEnvValue -Value $value
}
}
return $values
}
function ConvertTo-DotEnvBoolean {
param(
[Parameter(Mandatory = $true)]
[string]$Value,
[Parameter(Mandatory = $true)]
[string]$Key
)
switch -Regex ($Value.Trim()) {
'^(1|true|yes|y|on)$' { return $true }
'^(0|false|no|n|off)$' { return $false }
default { throw "Unable to parse boolean value '$Value' for $Key in the .env configuration." }
}
}
function ConvertTo-DotEnvArray {
param(
[Parameter(Mandatory = $true)]
[string]$Value
)
@($Value -split ';' | ForEach-Object { $_.Trim() } | Where-Object { -not [string]::IsNullOrWhiteSpace($_) })
}
function Set-SettingSource {
param(
[Parameter(Mandatory = $true)]
[hashtable]$Map,
[Parameter(Mandatory = $true)]
[string]$Name,
[Parameter(Mandatory = $true)]
[string]$Source
)
$Map[$Name] = $Source
}
function Get-SettingSourceLabel {
param(
[Parameter(Mandatory = $true)]
[hashtable]$Map,
[Parameter(Mandatory = $true)]
[string]$Name
)
if ($Map.ContainsKey($Name)) {
return [string]$Map[$Name]
}
return 'default'
}
function Get-DotEnvSettingValue {
param(
[Parameter(Mandatory = $true)]
[hashtable]$DotEnvValues,
[Parameter(Mandatory = $true)]
[string[]]$Keys
)
foreach ($key in $Keys) {
if ($DotEnvValues.ContainsKey($key)) {
return [pscustomobject]@{
Found = $true
Key = $key
Value = $DotEnvValues[$key]
}
}
}
return [pscustomobject]@{
Found = $false
Key = $null
Value = $null
}
}
function Set-ValueFromDotEnv {
param(
[Parameter(Mandatory = $true)]
[string]$ParameterName,
[Parameter(Mandatory = $true)]
[string[]]$DotEnvKeys,
[Parameter(Mandatory = $true)]
[scriptblock]$Transform
)
if ($script:CommandLineParameterNames -contains $ParameterName) {
return
}
$resolvedSetting = Get-DotEnvSettingValue -DotEnvValues $dotEnvValues -Keys $DotEnvKeys
if (-not $resolvedSetting.Found) {
return
}
$resolvedValue = & $Transform $resolvedSetting.Value $resolvedSetting.Key
$ExecutionContext.SessionState.PSVariable.Set("script:$ParameterName", $resolvedValue)
Set-SettingSource -Map $settingSources -Name $ParameterName -Source ".env ($($resolvedSetting.Key))"
}
function Resolve-AuthenticationSetting {
param(
[Parameter(Mandatory = $true)]
[string]$PrimaryParameterName,
[Parameter(Mandatory = $true)]
[string]$FallbackParameterName,
[Parameter(Mandatory = $true)]
[string]$FriendlyName
)
$primaryValue = Get-Variable -Name $PrimaryParameterName -Scope Script -ValueOnly
if (-not [string]::IsNullOrWhiteSpace($primaryValue)) {
return [pscustomobject]@{
Value = $primaryValue
Source = Get-SettingSourceLabel -Map $settingSources -Name $PrimaryParameterName
}
}
$fallbackValue = Get-Variable -Name $FallbackParameterName -Scope Script -ValueOnly
if (-not [string]::IsNullOrWhiteSpace($fallbackValue)) {
return [pscustomobject]@{
Value = $fallbackValue
Source = "$FallbackParameterName fallback [$((Get-SettingSourceLabel -Map $settingSources -Name $FallbackParameterName))]"
}
}
throw "$FriendlyName must be provided either via $PrimaryParameterName or via the legacy $FallbackParameterName setting."
}
$dotEnvValues = @{}
$settingSources = @{}
$script:CommandLineParameterNames = @($PSBoundParameters.Keys)
$isDefaultEnvFile = [string]::Equals($EnvFile, '.env', [System.StringComparison]::OrdinalIgnoreCase)
if (-not [string]::IsNullOrWhiteSpace($EnvFile)) {
if (Test-Path -LiteralPath $EnvFile) {
$dotEnvValues = Read-DotEnvFile -Path $EnvFile
Write-Verbose "Loaded configuration defaults from '$EnvFile'."
}
elseif (-not $isDefaultEnvFile) {
throw "The specified EnvFile '$EnvFile' could not be found."
}
}
foreach ($boundParameterName in $PSBoundParameters.Keys) {
Set-SettingSource -Map $settingSources -Name $boundParameterName -Source 'command line'
}
Set-ValueFromDotEnv -ParameterName 'SourceUserPrincipalName' -DotEnvKeys @('SOURCE_USER_PRINCIPAL_NAME') -Transform {
param($value)
$value
}
Set-ValueFromDotEnv -ParameterName 'TargetUserPrincipalName' -DotEnvKeys @('TARGET_USER_PRINCIPAL_NAME') -Transform {
param($value)
$value
}
Set-ValueFromDotEnv -ParameterName 'SourceFolderPath' -DotEnvKeys @('SOURCE_FOLDER_PATH') -Transform {
param($value)
$value
}
Set-ValueFromDotEnv -ParameterName 'TargetFolderPath' -DotEnvKeys @('TARGET_FOLDER_PATH') -Transform {
param($value)
$value
}
Set-ValueFromDotEnv -ParameterName 'SourceTenantId' -DotEnvKeys @('SOURCE_TENANT_ID') -Transform {
param($value)
$value
}
Set-ValueFromDotEnv -ParameterName 'SourceClientId' -DotEnvKeys @('SOURCE_CLIENT_ID') -Transform {
param($value)
$value
}
Set-ValueFromDotEnv -ParameterName 'SourceCertificateThumbprint' -DotEnvKeys @('SOURCE_CERTIFICATE_THUMBPRINT') -Transform {
param($value)
$value
}
Set-ValueFromDotEnv -ParameterName 'TargetTenantId' -DotEnvKeys @('TARGET_TENANT_ID') -Transform {
param($value)
$value
}
Set-ValueFromDotEnv -ParameterName 'TargetClientId' -DotEnvKeys @('TARGET_CLIENT_ID') -Transform {
param($value)
$value
}
Set-ValueFromDotEnv -ParameterName 'TargetCertificateThumbprint' -DotEnvKeys @('TARGET_CERTIFICATE_THUMBPRINT') -Transform {
param($value)
$value
}
Set-ValueFromDotEnv -ParameterName 'TenantId' -DotEnvKeys @('TENANT_ID') -Transform {
param($value)
$value
}
Set-ValueFromDotEnv -ParameterName 'ClientId' -DotEnvKeys @('CLIENT_ID') -Transform {
param($value)
$value
}
Set-ValueFromDotEnv -ParameterName 'CertificateThumbprint' -DotEnvKeys @('CERTIFICATE_THUMBPRINT') -Transform {
param($value)
$value
}
Set-ValueFromDotEnv -ParameterName 'ImportDirectlyIntoTargetFolder' -DotEnvKeys @('IMPORT_DIRECTLY_INTO_TARGET_FOLDER') -Transform {
param($value, $key)
ConvertTo-DotEnvBoolean -Value $value -Key $key
}
Set-ValueFromDotEnv -ParameterName 'OverlayMode' -DotEnvKeys @('OVERLAY_MODE') -Transform {
param($value, $key)
ConvertTo-DotEnvBoolean -Value $value -Key $key
}
Set-ValueFromDotEnv -ParameterName 'CopyEmptyFolders' -DotEnvKeys @('COPY_EMPTY_FOLDERS') -Transform {
param($value, $key)
ConvertTo-DotEnvBoolean -Value $value -Key $key
}
Set-ValueFromDotEnv -ParameterName 'IncludeFolderPath' -DotEnvKeys @('INCLUDE_FOLDER_PATH') -Transform {
param($value)
ConvertTo-DotEnvArray -Value $value
}
Set-ValueFromDotEnv -ParameterName 'ExcludeFolderPath' -DotEnvKeys @('EXCLUDE_FOLDER_PATH') -Transform {
param($value)
ConvertTo-DotEnvArray -Value $value
}
Set-ValueFromDotEnv -ParameterName 'Oldest' -DotEnvKeys @('OLDEST') -Transform {
param($value)
$value
}
Set-ValueFromDotEnv -ParameterName 'Newest' -DotEnvKeys @('NEWEST') -Transform {
param($value)
$value
}
Set-ValueFromDotEnv -ParameterName 'PreflightOnly' -DotEnvKeys @('PREFLIGHT_ONLY') -Transform {
param($value, $key)
ConvertTo-DotEnvBoolean -Value $value -Key $key
}
Set-ValueFromDotEnv -ParameterName 'Force' -DotEnvKeys @('FORCE') -Transform {
param($value, $key)
ConvertTo-DotEnvBoolean -Value $value -Key $key
}
Set-ValueFromDotEnv -ParameterName 'ExportBatchSize' -DotEnvKeys @('EXPORT_BATCH_SIZE') -Transform {
param($value, $key)
$parsedExportBatchSize = 0
if (-not [int]::TryParse($value, [ref]$parsedExportBatchSize)) {
throw "Unable to parse integer value '$value' for $key in the .env configuration."
}
$parsedExportBatchSize
}
if ([string]::IsNullOrWhiteSpace($SourceUserPrincipalName)) {
throw 'SourceUserPrincipalName must be provided either on the command line or in the .env configuration.'
}
if ([string]::IsNullOrWhiteSpace($TargetUserPrincipalName)) {
throw 'TargetUserPrincipalName must be provided either on the command line or in the .env configuration.'
}
if ([string]::IsNullOrWhiteSpace($SourceFolderPath)) {
$SourceFolderPath = '\'
Set-SettingSource -Map $settingSources -Name 'SourceFolderPath' -Source 'defaulted to mailbox root'
}
$sourceAuthenticationSettings = @{
Tenant = Resolve-AuthenticationSetting -PrimaryParameterName 'SourceTenantId' -FallbackParameterName 'TenantId' -FriendlyName 'Source tenant ID'
Client = Resolve-AuthenticationSetting -PrimaryParameterName 'SourceClientId' -FallbackParameterName 'ClientId' -FriendlyName 'Source client ID'
Certificate = Resolve-AuthenticationSetting -PrimaryParameterName 'SourceCertificateThumbprint' -FallbackParameterName 'CertificateThumbprint' -FriendlyName 'Source certificate thumbprint'
}
$targetAuthenticationSettings = @{
Tenant = Resolve-AuthenticationSetting -PrimaryParameterName 'TargetTenantId' -FallbackParameterName 'TenantId' -FriendlyName 'Target tenant ID'
Client = Resolve-AuthenticationSetting -PrimaryParameterName 'TargetClientId' -FallbackParameterName 'ClientId' -FriendlyName 'Target client ID'
Certificate = Resolve-AuthenticationSetting -PrimaryParameterName 'TargetCertificateThumbprint' -FallbackParameterName 'CertificateThumbprint' -FriendlyName 'Target certificate thumbprint'
}
if ($ExportBatchSize -lt 1 -or $ExportBatchSize -gt 20) {
throw 'ExportBatchSize must be between 1 and 20 because Graph exportItems accepts at most 20 item IDs per request.'
}
if ($IncludeFolderPath -and $ExcludeFolderPath) {
throw 'IncludeFolderPath and ExcludeFolderPath are mutually exclusive. Specify only one of them.'
}
if ($OverlayMode -and $ImportDirectlyIntoTargetFolder) {
throw 'OverlayMode and ImportDirectlyIntoTargetFolder cannot be used together. OverlayMode already merges directly into the target structure.'
}
function Resolve-DateFilterBoundary {
param(
[Parameter(Mandatory = $true)]
[string]$Value,
[Parameter(Mandatory = $true)]
[ValidateSet('Oldest', 'Newest')]
[string]$Boundary
)
$trimmedValue = $Value.Trim()
if ([string]::IsNullOrWhiteSpace($trimmedValue)) {
throw "$Boundary cannot be empty when specified."
}
if ($trimmedValue -match '^\d{4}-\d{2}-\d{2}$') {
$dateOnly = [datetime]::ParseExact($trimmedValue, 'yyyy-MM-dd', [System.Globalization.CultureInfo]::InvariantCulture)
$comparisonOperator = if ($Boundary -eq 'Oldest') { 'ge' } else { 'lt' }
$comparisonValue = if ($Boundary -eq 'Oldest') {
$dateOnly.ToString('yyyy-MM-dd', [System.Globalization.CultureInfo]::InvariantCulture)
}
else {
$dateOnly.AddDays(1).ToString('yyyy-MM-dd', [System.Globalization.CultureInfo]::InvariantCulture)
}
return [pscustomobject]@{
RawValue = $trimmedValue
IsDateOnly = $true
InclusiveLowerBound = if ($Boundary -eq 'Oldest') { $dateOnly.Date } else { $dateOnly.Date.AddDays(1).AddTicks(-1) }
FilterClause = "createdDateTime $comparisonOperator $comparisonValue"
}
}
try {
$parsedDate = [datetimeoffset]::Parse($trimmedValue, [System.Globalization.CultureInfo]::InvariantCulture)
}
catch {
throw "Unable to parse $Boundary value '$trimmedValue' as a date or timestamp."
}
$utcDate = $parsedDate.ToUniversalTime()
$formattedUtcDate = $utcDate.ToString('yyyy-MM-ddTHH:mm:ssZ', [System.Globalization.CultureInfo]::InvariantCulture)
$comparisonOperator = if ($Boundary -eq 'Oldest') { 'ge' } else { 'le' }
return [pscustomobject]@{
RawValue = $trimmedValue
IsDateOnly = $false
InclusiveLowerBound = $utcDate.UtcDateTime
FilterClause = "createdDateTime $comparisonOperator $formattedUtcDate"
}
}
function New-MailboxItemDateFilter {
param(
[AllowNull()]
[string]$Oldest,
[AllowNull()]
[string]$Newest
)
if ([string]::IsNullOrWhiteSpace($Oldest) -and [string]::IsNullOrWhiteSpace($Newest)) {
return $null
}
$oldestBoundary = if ([string]::IsNullOrWhiteSpace($Oldest)) { $null } else { Resolve-DateFilterBoundary -Value $Oldest -Boundary Oldest }
$newestBoundary = if ([string]::IsNullOrWhiteSpace($Newest)) { $null } else { Resolve-DateFilterBoundary -Value $Newest -Boundary Newest }
if ($oldestBoundary -and $newestBoundary) {
if ($oldestBoundary.InclusiveLowerBound -gt $newestBoundary.InclusiveLowerBound) {
throw "Oldest value '$Oldest' must be earlier than or equal to Newest value '$Newest'."
}
}
$filterClauses = @(
if ($oldestBoundary) { $oldestBoundary.FilterClause }
if ($newestBoundary) { $newestBoundary.FilterClause }
)
[pscustomobject]@{
Oldest = $oldestBoundary
Newest = $newestBoundary
FilterText = ($filterClauses -join ' and ')
}
}
function Write-StatusMessage {
param(
[Parameter(Mandatory = $true)]
[string]$Message
)
Write-Information -MessageData $Message -InformationAction Continue
}
function Get-ExecutionModeSummary {
param(
[Parameter(Mandatory = $true)]
[switch]$OverlayMode,
[Parameter(Mandatory = $true)]
[switch]$ImportDirectlyIntoTargetFolder,
[Parameter(Mandatory = $true)]
[switch]$PreflightOnly
)
if ($PreflightOnly) {
return 'PreflightOnly'
}
if ($OverlayMode) {
return 'Overlay'
}
if ($ImportDirectlyIntoTargetFolder) {
return 'DirectImport'
}
return 'StructuredCopy'
}
function Confirm-PlannedOperation {
param(
[Parameter(Mandatory = $true)]
[string]$SourceUserPrincipalName,
[Parameter(Mandatory = $true)]
[string]$TargetUserPrincipalName,
[Parameter(Mandatory = $true)]
[string]$SourceFolderPath,
[Parameter(Mandatory = $true)]
[string]$ResolvedTargetDescription,
[Parameter(Mandatory = $true)]
[hashtable]$SourceAuthenticationSettings,
[Parameter(Mandatory = $true)]
[hashtable]$TargetAuthenticationSettings,
[Parameter(Mandatory = $true)]
[string]$Mode,
[Parameter(Mandatory = $true)]
[switch]$OverlayMode,
[Parameter(Mandatory = $true)]
[switch]$ImportDirectlyIntoTargetFolder,
[AllowNull()]
[object]$DateFilter,
[AllowNull()]
[string[]]$IncludeFolderPath,
[AllowNull()]
[string[]]$ExcludeFolderPath,
[Parameter(Mandatory = $true)]
[hashtable]$SettingSources,
[Parameter(Mandatory = $true)]
[int]$EstimatedSelectedFolderCount,
[Parameter(Mandatory = $true)]
[int]$EstimatedTraversedFolderCount,
[Parameter(Mandatory = $true)]
[int]$EstimatedItemCount,
[Parameter(Mandatory = $true)]
[switch]$CopyEmptyFolders,
[Parameter(Mandatory = $true)]
[switch]$PreflightOnly,
[Parameter(Mandatory = $true)]
[switch]$WhatIfMode,
[Parameter(Mandatory = $true)]
[switch]$Force
)
$sourceMailboxSource = Get-SettingSourceLabel -Map $SettingSources -Name 'SourceUserPrincipalName'
$targetMailboxSource = Get-SettingSourceLabel -Map $SettingSources -Name 'TargetUserPrincipalName'
$sourcePathSource = Get-SettingSourceLabel -Map $SettingSources -Name 'SourceFolderPath'
$targetPathSource = Get-SettingSourceLabel -Map $SettingSources -Name 'TargetFolderPath'
$copyEmptySource = Get-SettingSourceLabel -Map $SettingSources -Name 'CopyEmptyFolders'
$modeSource = if ($PreflightOnly -and $SettingSources.ContainsKey('PreflightOnly')) {
Get-SettingSourceLabel -Map $SettingSources -Name 'PreflightOnly'
}
elseif ($ImportDirectlyIntoTargetFolder -and $SettingSources.ContainsKey('ImportDirectlyIntoTargetFolder')) {
Get-SettingSourceLabel -Map $SettingSources -Name 'ImportDirectlyIntoTargetFolder'
}
elseif ($OverlayMode -and $SettingSources.ContainsKey('OverlayMode')) {
Get-SettingSourceLabel -Map $SettingSources -Name 'OverlayMode'
}
else {
'default'
}
Write-StatusMessage -Message 'Planned operation:'
Write-StatusMessage -Message (" Source mailbox : {0} [{1}]" -f $SourceUserPrincipalName, $sourceMailboxSource)
Write-StatusMessage -Message (" Target mailbox : {0} [{1}]" -f $TargetUserPrincipalName, $targetMailboxSource)
Write-StatusMessage -Message (" Source path : {0} [{1}]" -f $SourceFolderPath, $sourcePathSource)
Write-StatusMessage -Message (" Target : {0} [{1}]" -f $ResolvedTargetDescription, $targetPathSource)
Write-StatusMessage -Message (" Source tenant : {0} [{1}]" -f $SourceAuthenticationSettings.Tenant.Value, $SourceAuthenticationSettings.Tenant.Source)
Write-StatusMessage -Message (" Source client : {0} [{1}]" -f $SourceAuthenticationSettings.Client.Value, $SourceAuthenticationSettings.Client.Source)
Write-StatusMessage -Message (" Source cert : {0} [{1}]" -f $SourceAuthenticationSettings.Certificate.Value, $SourceAuthenticationSettings.Certificate.Source)
Write-StatusMessage -Message (" Target tenant : {0} [{1}]" -f $TargetAuthenticationSettings.Tenant.Value, $TargetAuthenticationSettings.Tenant.Source)
Write-StatusMessage -Message (" Target client : {0} [{1}]" -f $TargetAuthenticationSettings.Client.Value, $TargetAuthenticationSettings.Client.Source)
Write-StatusMessage -Message (" Target cert : {0} [{1}]" -f $TargetAuthenticationSettings.Certificate.Value, $TargetAuthenticationSettings.Certificate.Source)
Write-StatusMessage -Message (" Mode : {0} [{1}]" -f $Mode, $modeSource)
Write-StatusMessage -Message (" Copy empty : {0} [{1}]" -f ($(if ($CopyEmptyFolders) { 'Yes' } else { 'No' })), $copyEmptySource)
Write-StatusMessage -Message (" Est. folders : {0} selected, {1} traversed" -f $EstimatedSelectedFolderCount, $EstimatedTraversedFolderCount)
Write-StatusMessage -Message (" Est. items : {0}" -f $EstimatedItemCount)
if ($DateFilter) {
$dateFilterSource = if ($SettingSources.ContainsKey('Oldest') -or $SettingSources.ContainsKey('Newest')) {
if ($SettingSources.ContainsKey('Oldest')) {
Get-SettingSourceLabel -Map $SettingSources -Name 'Oldest'
}
else {
Get-SettingSourceLabel -Map $SettingSources -Name 'Newest'
}
}
else {
'default'
}
Write-StatusMessage -Message (" Date filter : {0} [{1}]" -f $DateFilter.FilterText, $dateFilterSource)
}
else {
Write-StatusMessage -Message ' Date filter : None [default]'
}
if ($IncludeFolderPath) {
Write-StatusMessage -Message (" Include paths : {0} [{1}]" -f (($IncludeFolderPath | ForEach-Object { Format-FolderPath -Path $_ }) -join ', '), (Get-SettingSourceLabel -Map $SettingSources -Name 'IncludeFolderPath'))
}
elseif ($ExcludeFolderPath) {
Write-StatusMessage -Message (" Exclude paths : {0} [{1}]" -f (($ExcludeFolderPath | ForEach-Object { Format-FolderPath -Path $_ }) -join ', '), (Get-SettingSourceLabel -Map $SettingSources -Name 'ExcludeFolderPath'))
}
else {
Write-StatusMessage -Message ' Folder filter : None [default]'
}
Write-StatusMessage -Message (" WhatIf : {0} [{1}]" -f ($(if ($WhatIfMode) { 'Yes' } else { 'No' })), 'command line/session')
Write-StatusMessage -Message (" Preflight only : {0} [{1}]" -f ($(if ($PreflightOnly) { 'Yes' } else { 'No' })), (Get-SettingSourceLabel -Map $SettingSources -Name 'PreflightOnly'))
if ($Force) {
Write-Verbose 'Skipping confirmation because Force was specified.'
return
}
if ($PreflightOnly) {
Write-Verbose 'Skipping confirmation because PreflightOnly was specified.'
return
}
if ($WhatIfMode) {
Write-Verbose 'Skipping confirmation because WhatIf was specified.'
return
}
$caption = 'Confirm mailbox copy'
$message = 'Proceed with this mailbox operation?'
$hostUi = $null
try {
$hostUi = $Host.UI
}
catch {
$hostUi = $null
}
if ($null -eq $hostUi) {
throw 'Confirmation is not available in this host. Re-run with -Force to continue without a prompt.'
}
if (-not $PSCmdlet.ShouldContinue($message, $caption)) {
throw 'Operation cancelled by user.'
}
}
function ConvertTo-Base64Url {
param(
[Parameter(Mandatory = $true)]
[byte[]]$Bytes
)
[Convert]::ToBase64String($Bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_')
}
function Get-ClientCertificate {
param(
[Parameter(Mandatory = $true)]
[string]$Thumbprint
)
$normalizedThumbprint = $Thumbprint.Replace(' ', '').ToUpperInvariant()
$certificate = Get-ChildItem -Path Cert:\CurrentUser\My |
Where-Object Thumbprint -eq $normalizedThumbprint |
Select-Object -First 1
if (-not $certificate) {
throw "Certificate '$normalizedThumbprint' was not found in Cert:\CurrentUser\My."
}
if (-not $certificate.HasPrivateKey) {
throw "Certificate '$normalizedThumbprint' does not have an accessible private key."
}
return $certificate
}
function New-ClientAssertionJwt {
param(
[Parameter(Mandatory = $true)]
[string]$TenantId,
[Parameter(Mandatory = $true)]
[string]$ClientId,
[Parameter(Mandatory = $true)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate
)
$tokenEndpoint = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"
$now = [DateTimeOffset]::UtcNow
$headerJson = @{
alg = 'RS256'
typ = 'JWT'
x5t = ConvertTo-Base64Url -Bytes $Certificate.GetCertHash()
} | ConvertTo-Json -Compress
$payloadJson = @{
aud = $tokenEndpoint
iss = $ClientId
sub = $ClientId
jti = [guid]::NewGuid().Guid
nbf = $now.ToUnixTimeSeconds()
exp = $now.AddMinutes(10).ToUnixTimeSeconds()
} | ConvertTo-Json -Compress
$headerEncoded = ConvertTo-Base64Url -Bytes ([Text.Encoding]::UTF8.GetBytes($headerJson))
$payloadEncoded = ConvertTo-Base64Url -Bytes ([Text.Encoding]::UTF8.GetBytes($payloadJson))
$unsignedToken = "$headerEncoded.$payloadEncoded"
$rsa = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($Certificate)
if (-not $rsa) {
throw "Unable to access the private key for certificate '$($Certificate.Thumbprint)'."
}
try {
$signatureBytes = $rsa.SignData(
[Text.Encoding]::UTF8.GetBytes($unsignedToken),
[Security.Cryptography.HashAlgorithmName]::SHA256,
[Security.Cryptography.RSASignaturePadding]::Pkcs1
)
}
finally {
$rsa.Dispose()
}
$signatureEncoded = ConvertTo-Base64Url -Bytes $signatureBytes
return "$unsignedToken.$signatureEncoded"
}
function Get-GraphAccessToken {
param(
[Parameter(Mandatory = $true)]
[string]$TenantId,
[Parameter(Mandatory = $true)]
[string]$ClientId,
[Parameter(Mandatory = $true)]
[string]$CertificateThumbprint
)
(Get-GraphAccessTokenRecord `
-TenantId $TenantId `
-ClientId $ClientId `
-CertificateThumbprint $CertificateThumbprint
).AccessToken
}
function Get-GraphAccessTokenRecord {
param(
[Parameter(Mandatory = $true)]
[string]$TenantId,
[Parameter(Mandatory = $true)]
[string]$ClientId,
[Parameter(Mandatory = $true)]
[string]$CertificateThumbprint
)
$certificate = Get-ClientCertificate -Thumbprint $CertificateThumbprint
$clientAssertion = New-ClientAssertionJwt -TenantId $TenantId -ClientId $ClientId -Certificate $certificate
$tokenEndpoint = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"
$issuedAtUtc = [DateTimeOffset]::UtcNow
$tokenResponse = Invoke-RestMethod -Method Post -Uri $tokenEndpoint -ContentType 'application/x-www-form-urlencoded' -Body @{
client_id = $ClientId
scope = 'https://graph.microsoft.com/.default'
grant_type = 'client_credentials'
client_assertion_type = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'
client_assertion = $clientAssertion
}
if (-not $tokenResponse.access_token) {
throw 'Access token request did not return an access_token value.'
}
$expiresInSeconds = 3600
if ($tokenResponse.PSObject.Properties['expires_in']) {
[void][int]::TryParse([string]$tokenResponse.expires_in, [ref]$expiresInSeconds)
}
[pscustomobject]@{
AccessToken = [string]$tokenResponse.access_token
ExpiresAtUtc = $issuedAtUtc.AddSeconds($expiresInSeconds)
}
}
function New-GraphAuthenticationContext {
param(
[Parameter(Mandatory = $true)]
[string]$TenantId,
[Parameter(Mandatory = $true)]
[string]$ClientId,
[Parameter(Mandatory = $true)]
[string]$CertificateThumbprint
)
[pscustomobject]@{
TenantId = $TenantId
ClientId = $ClientId
CertificateThumbprint = $CertificateThumbprint
AccessToken = $null
ExpiresAtUtc = [DateTimeOffset]::MinValue
}
}
function Test-IsGraphAuthenticationContext {
param(
[AllowNull()]
[object]$Value
)
if ($null -eq $Value) {
return $false
}
foreach ($propertyName in @('TenantId', 'ClientId', 'CertificateThumbprint', 'AccessToken', 'ExpiresAtUtc')) {
if (-not $Value.PSObject.Properties[$propertyName]) {
return $false
}
}
return $true
}
function Resolve-GraphAccessToken {
param(
[Parameter(Mandatory = $true)]
[object]$AccessToken,
[switch]$ForceRefresh
)
if (-not (Test-IsGraphAuthenticationContext -Value $AccessToken)) {
return [string]$AccessToken
}
$refreshThresholdUtc = [DateTimeOffset]::UtcNow.AddMinutes(5)
if (
-not $ForceRefresh -and
-not [string]::IsNullOrWhiteSpace([string]$AccessToken.AccessToken) -and
$null -ne $AccessToken.ExpiresAtUtc -and
([DateTimeOffset]$AccessToken.ExpiresAtUtc) -gt $refreshThresholdUtc
) {
return [string]$AccessToken.AccessToken
}
Write-Verbose "Refreshing Microsoft Graph access token for client '$($AccessToken.ClientId)' in tenant '$($AccessToken.TenantId)'."
$tokenRecord = Get-GraphAccessTokenRecord `
-TenantId $AccessToken.TenantId `
-ClientId $AccessToken.ClientId `
-CertificateThumbprint $AccessToken.CertificateThumbprint
$AccessToken.AccessToken = $tokenRecord.AccessToken
$AccessToken.ExpiresAtUtc = $tokenRecord.ExpiresAtUtc
[string]$AccessToken.AccessToken
}
function Get-HttpStatusCodeFromException {
param(
[Parameter(Mandatory = $true)]
[System.Exception]$Exception
)
if ($Exception.PSObject.Properties['Response'] -and $null -ne $Exception.Response) {
$statusCodeProperty = $Exception.Response.PSObject.Properties['StatusCode']
if ($statusCodeProperty -and $null -ne $statusCodeProperty.Value) {
return [int]$statusCodeProperty.Value
}
}
return $null
}
function Invoke-GraphApiRequest {
param(
[Parameter(Mandatory = $true)]
[object]$AccessToken,
[Parameter(Mandatory = $true)]
[string]$Uri,
[ValidateSet('GET', 'POST', 'PATCH', 'DELETE')]
[string]$Method = 'GET',
[hashtable]$Headers,
$Body
)
$resolvedUri = if ($Uri -match '^https://') {
$Uri
}
else {
"https://graph.microsoft.com$Uri"
}
$attemptCount = 0
while ($true) {
$attemptCount++
$resolvedAccessToken = Resolve-GraphAccessToken -AccessToken $AccessToken -ForceRefresh:($attemptCount -gt 1)
$invokeParams = @{
Method = $Method
Uri = $resolvedUri
Headers = @{
Authorization = "Bearer $resolvedAccessToken"
}
}
if ($Headers) {
foreach ($headerKey in $Headers.Keys) {
$invokeParams.Headers[$headerKey] = $Headers[$headerKey]
}
}
if ($null -ne $Body) {
$invokeParams.ContentType = 'application/json'
$invokeParams.Body = $Body | ConvertTo-Json -Depth 10 -Compress
}
try {
return Invoke-RestMethod @invokeParams
}