Repository navigation
Expand file tree
/
Copy pathUpload-ToSharePoint.ps1
More file actions
790 lines (669 loc) · 31.1 KB
/
Copy pathUpload-ToSharePoint.ps1
File metadata and controls
790 lines (669 loc) · 31.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
<#
.SYNOPSIS
Uploads a local folder tree into a SharePoint document library, preserving the
Created and Modified timestamps of both files and folders.
.DESCRIPTION
A normal upload (drag-drop, OneDrive sync, Add-PnPFile) stamps every file with
the upload time. This script uploads over the Microsoft Graph API and then sets
each item's fileSystemInfo, so the dates shown in SharePoint match the local
files -- which Export-OneNoteMarkdown.ps1 in turn stamps from the OneNote pages.
FOLDER dates need a second step. Graph's fileSystemInfo is a client-supplied
facet: SharePoint surfaces it as the Modified column for files, but for folders
the library keeps its own value and ignores it. So folders are stamped through
PnP.PowerShell instead, using a list item SystemUpdate, which SharePoint does
honour. That happens in a final pass after every upload, because sending a file
into a folder resets that folder's Modified date.
RUN THIS WITH POWERSHELL 7 (pwsh), not Windows PowerShell 5.1. PnP.PowerShell is
.NET Core only, so 5.1 cannot load it and folder dates will be skipped. Note this
is the opposite of Export-OneNoteMarkdown.ps1, which must run under 5.1 because
OneNote's COM interface does not work under 7.
Two sign-ins are therefore expected: Graph for the upload, SharePoint for the
folder dates. First-time setup:
Install-Module Microsoft.Graph.Authentication -Scope CurrentUser
Install-Module PnP.PowerShell -Scope CurrentUser
The Graph sign-in needs no app registration. The PnP sign-in uses an Entra app
registered for this tenant, whose client ID is built into the script -- override
with -ClientId or PNPPOWERSHELL_CLIENTID. Use -SkipFolderDates to upload without
the second sign-in. (The old shared 'PnP Management Shell' app is not usable for
this: PnP retired it on 9 September 2024.)
Files already in the library are skipped when their size and modified date
match the local file, so re-runs only send what changed.
.PARAMETER SourceFolder
Local folder whose contents (recursive) are uploaded. The folder itself is not
created remotely; its children land in -LibraryPath.
.PARAMETER SiteUrl
The SharePoint site, e.g. https://contoso.sharepoint.com/sites/Marketing
.PARAMETER LibraryPath
Document library, optionally followed by a subfolder path, using the library's
display name. Examples: 'Documents', 'Documents/OneNote Exports',
'Client Central/Exports'. Subfolders are created as needed.
.PARAMETER Force
Upload every file, even ones that look unchanged.
.PARAMETER ClientId
Entra app (client) ID for the SharePoint sign-in that sets folder dates.
Falls back to $env:PNPPOWERSHELL_CLIENTID.
.PARAMETER SkipFolderDates
Upload only. Folders keep the upload date; file dates are still preserved.
.PARAMETER FolderDatesOnly
Set the folder dates on a tree that is already uploaded, and nothing else. Needs
only the SharePoint sign-in, sends no files, and is safe to re-run.
.EXAMPLE
# Files are already in SharePoint; just fix the folder dates.
.\Upload-ToSharePoint.ps1 -SourceFolder .\out `
-SiteUrl https://contoso.sharepoint.com/sites/Marketing `
-LibraryPath 'Documents/OneNote Exports' -FolderDatesOnly
.EXAMPLE
.\Upload-ToSharePoint.ps1 -SourceFolder .\out `
-SiteUrl https://contoso.sharepoint.com/sites/Marketing `
-LibraryPath 'Documents/OneNote Exports' -ClientId '00000000-0000-0000-0000-000000000000'
.EXAMPLE
.\Upload-ToSharePoint.ps1 -SourceFolder .\out -SiteUrl ... -LibraryPath Documents -WhatIf
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[Parameter(Mandatory = $true)]
[string] $SourceFolder,
[Parameter(Mandatory = $true)]
[string] $SiteUrl,
[Parameter(Mandatory = $true)]
[string] $LibraryPath,
[switch] $Force,
# Entra app (client) ID used for the PnP sign-in that sets folder dates. Falls
# back to $env:PNPPOWERSHELL_CLIENTID. Omit to skip folder dates entirely.
[string] $ClientId,
[switch] $SkipFolderDates,
# Set the folder dates on an already-uploaded tree and do nothing else. Needs
# only the SharePoint sign-in -- no Graph, no files sent.
[switch] $FolderDatesOnly
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
# Graph upload-session chunks must be multiples of 320 KiB; ~3.75 MB is the sweet
# spot. Files at or below the simple-upload limit go up in one PUT.
$script:SimpleUploadLimit = 4MB
$script:ChunkSize = 12 * 320KB
# No client ID is shipped: an Entra app registration is specific to one tenant, so
# each organisation needs its own. Supply it with -ClientId or by setting
# PNPPOWERSHELL_CLIENTID once. See the README for how to create one.
$script:DefaultClientId = ''
#region Graph helpers
function Connect-Graph {
if (-not (Get-Module -ListAvailable -Name Microsoft.Graph.Authentication)) {
throw @"
The Microsoft.Graph.Authentication module is not installed. Install it once with:
Install-Module Microsoft.Graph.Authentication -Scope CurrentUser
then run this script again.
"@
}
Import-Module Microsoft.Graph.Authentication
$ctx = Get-MgContext
if (-not $ctx -or ($ctx.Scopes -notcontains 'Sites.ReadWrite.All')) {
Write-Host 'Signing in to Microsoft Graph (browser window)...' -ForegroundColor Cyan
Connect-MgGraph -Scopes 'Sites.ReadWrite.All' -NoWelcome
}
}
function Invoke-GraphRetry {
<#
Invoke-MgGraphRequest with backoff for throttling (429) and transient
5xx responses. Anything else rethrows immediately.
#>
param(
[string] $Method,
[string] $Uri,
$Body = $null,
[string] $ContentType = 'application/json'
)
for ($attempt = 1; $attempt -le 5; $attempt++) {
try {
if ($null -ne $Body) {
return Invoke-MgGraphRequest -Method $Method -Uri $Uri -Body $Body `
-ContentType $ContentType -OutputType PSObject
}
return Invoke-MgGraphRequest -Method $Method -Uri $Uri -OutputType PSObject
}
catch {
$msg = $_.Exception.Message
$transient = $msg -match '429|throttl|503|504|502|timeout'
if ($attempt -eq 5 -or -not $transient) { throw }
$delay = [Math]::Pow(2, $attempt)
Write-Verbose "Transient Graph error (attempt $attempt), retrying in ${delay}s: $msg"
Start-Sleep -Seconds $delay
}
}
}
function Get-EncodedPath {
# Graph path addressing needs each segment URL-encoded, slashes kept.
param([string] $Path)
$segs = $Path -split '/' | Where-Object { $_ -ne '' } |
ForEach-Object { [uri]::EscapeDataString($_) }
return ($segs -join '/')
}
function Get-GraphProp {
<#
Reads one property off a Graph response. Invoke-MgGraphRequest returns nested
objects as a hashtable or a PSObject depending on the SDK version, so neither
plain property access nor index access is safe on its own.
#>
param($Obj, [string] $Name)
if ($null -eq $Obj) { return $null }
if ($Obj -is [System.Collections.IDictionary]) {
# ContainsKey, not Contains: on Dictionary[string,object] PowerShell binds
# .Contains() to ICollection<KeyValuePair>.Contains and cannot resolve it.
# Hashtable and the generic dictionaries both expose ContainsKey.
if ($Obj.PSObject.Methods['ContainsKey']) {
if ($Obj.ContainsKey($Name)) { return $Obj[$Name] }
return $null
}
try { return $Obj[$Name] } catch { return $null }
}
$prop = $Obj.PSObject.Properties[$Name]
if ($prop) { return $prop.Value }
return $null
}
function Get-RemoteModifiedUtc {
<#
The remote fileSystemInfo modified date as UTC, or $null when it is absent or
unreadable. Never throws: an unknown remote date simply means the file cannot
be shown to be unchanged, so it gets uploaded again. The value may arrive as a
string, a DateTime or a DateTimeOffset.
#>
param($Item)
$raw = Get-GraphProp (Get-GraphProp $Item 'fileSystemInfo') 'lastModifiedDateTime'
if ($null -eq $raw) { return $null }
if ($raw -is [datetime]) { return $raw.ToUniversalTime() }
if ($raw -is [datetimeoffset]) { return $raw.UtcDateTime }
$text = [string]$raw
if ([string]::IsNullOrWhiteSpace($text)) { return $null }
$parsed = [datetime]::MinValue
$styles = [System.Globalization.DateTimeStyles]::AdjustToUniversal -bor
[System.Globalization.DateTimeStyles]::AssumeUniversal
if ([datetime]::TryParse($text, [System.Globalization.CultureInfo]::InvariantCulture,
$styles, [ref]$parsed)) {
return $parsed
}
Write-Verbose "Unreadable remote modified date '$text'; will re-upload."
return $null
}
function Get-DriveItem {
# Returns the driveItem at a drive-root-relative path, or $null when absent.
param([string] $DriveBase, [string] $Path)
$enc = Get-EncodedPath $Path
try {
return Invoke-GraphRetry -Method GET -Uri "$DriveBase/root:/${enc}?`$select=id,size,fileSystemInfo,folder,lastModifiedDateTime"
}
catch {
# Absent items surface differently per PS version: 'itemNotFound' (Graph
# error code), 'NotFound (Not Found)' (5.1 HttpClient) or a bare 404.
if ($_.Exception.Message -match '(?i)itemNotFound|NotFound|404') { return $null }
throw
}
}
#endregion
#region Resolve site, drive and base folder
function Resolve-TargetDrive {
param([string] $SiteUrl, [string] $LibraryPath)
$u = [uri]$SiteUrl
$siteId = "$($u.Host):$($u.AbsolutePath.TrimEnd('/'))"
$site = Invoke-GraphRetry -Method GET -Uri "https://graph.microsoft.com/v1.0/sites/$siteId"
Write-Host "Site : $($site.displayName)" -ForegroundColor Cyan
$segments = @($LibraryPath -split '/' | Where-Object { $_ -ne '' })
$libName = $segments[0]
$drives = (Invoke-GraphRetry -Method GET -Uri "https://graph.microsoft.com/v1.0/sites/$($site.id)/drives?`$select=id,name,webUrl").value
# Match the display name ('Documents') or the URL segment ('Shared Documents').
$drive = $drives | Where-Object {
$_.name -eq $libName -or
([uri]::UnescapeDataString(([uri]$_.webUrl).Segments[-1].TrimEnd('/')) -eq $libName)
} | Select-Object -First 1
if (-not $drive) {
$names = ($drives | ForEach-Object { ' - ' + $_.name }) -join "`r`n"
throw "No document library called '$libName' on that site. Libraries found:`r`n$names"
}
Write-Host "Library: $($drive.name)" -ForegroundColor Cyan
$baseFolder = ''
if ($segments.Count -gt 1) { $baseFolder = ($segments[1..($segments.Count - 1)] -join '/') }
return [pscustomobject]@{
DriveBase = "https://graph.microsoft.com/v1.0/drives/$($drive.id)"
BaseFolder = $baseFolder
DriveWebUrl = $drive.webUrl
}
}
$script:KnownFolders = @{}
function Confirm-RemoteFolder {
# Creates the folder chain (if needed) for a drive-root-relative folder path.
param([string] $DriveBase, [string] $Path)
if ([string]::IsNullOrEmpty($Path)) { return }
if ($script:KnownFolders.ContainsKey($Path)) { return }
$parts = $Path -split '/'
$sofar = ''
foreach ($part in $parts) {
$parent = $sofar
if ($sofar) { $sofar = "$sofar/$part" } else { $sofar = $part }
if ($script:KnownFolders.ContainsKey($sofar)) { continue }
if (-not (Get-DriveItem -DriveBase $DriveBase -Path $sofar)) {
$parentUri = "$DriveBase/root/children"
if ($parent) { $parentUri = "$DriveBase/root:/$(Get-EncodedPath $parent):/children" }
$body = @{ name = $part; folder = @{}; '@microsoft.graph.conflictBehavior' = 'fail' } | ConvertTo-Json
try { Invoke-GraphRetry -Method POST -Uri $parentUri -Body $body | Out-Null }
catch { if ($_.Exception.Message -notmatch 'nameAlreadyExists') { throw } }
}
$script:KnownFolders[$sofar] = $true
}
}
#endregion
#region Upload
function Send-FileToDrive {
# Uploads one file and stamps its fileSystemInfo from the local timestamps.
param([string] $DriveBase, [System.IO.FileInfo] $File, [string] $RemotePath)
$enc = Get-EncodedPath $RemotePath
if ($File.Length -le $script:SimpleUploadLimit) {
$bytes = [System.IO.File]::ReadAllBytes($File.FullName)
$item = Invoke-GraphRetry -Method PUT -Uri "$DriveBase/root:/${enc}:/content" `
-Body $bytes -ContentType 'application/octet-stream'
}
else {
# Chunked upload session for large files.
$sessionBody = @{ item = @{ '@microsoft.graph.conflictBehavior' = 'replace' } } | ConvertTo-Json
$session = Invoke-GraphRetry -Method POST -Uri "$DriveBase/root:/${enc}:/createUploadSession" -Body $sessionBody
$stream = [System.IO.File]::OpenRead($File.FullName)
try {
$buffer = New-Object byte[] $script:ChunkSize
$pos = [long]0
$item = $null
while ($pos -lt $File.Length) {
$read = $stream.Read($buffer, 0, $buffer.Length)
$chunk = $buffer
if ($read -lt $buffer.Length) { $chunk = $buffer[0..($read - 1)] }
$range = 'bytes {0}-{1}/{2}' -f $pos, ($pos + $read - 1), $File.Length
# The session URL is pre-authenticated; plain web request, no token.
$resp = Invoke-WebRequest -Method Put -Uri $session.uploadUrl `
-Headers @{ 'Content-Range' = $range } -Body $chunk -UseBasicParsing
$pos += $read
if ($resp.StatusCode -in 200, 201) { $item = $resp.Content | ConvertFrom-Json }
}
}
finally { $stream.Close() }
}
# The whole point: mirror the local Created / Modified dates onto SharePoint.
Set-DriveItemTimestamps -DriveBase $DriveBase -ItemId $item.id `
-CreatedUtc $File.CreationTimeUtc -ModifiedUtc $File.LastWriteTimeUtc
}
function Set-DriveItemTimestamps {
# Stamps an existing drive item -- file or folder -- with the given dates.
param([string] $DriveBase, [string] $ItemId, [datetime] $CreatedUtc, [datetime] $ModifiedUtc)
$body = @{
fileSystemInfo = @{
createdDateTime = $CreatedUtc.ToString('yyyy-MM-ddTHH:mm:ssZ')
lastModifiedDateTime = $ModifiedUtc.ToString('yyyy-MM-ddTHH:mm:ssZ')
}
} | ConvertTo-Json
Invoke-GraphRetry -Method PATCH -Uri "$DriveBase/items/$ItemId" -Body $body | Out-Null
}
#endregion
#region Folder dates via PnP
function Set-FolderDatesWithPnP {
<#
Sets the Created / Modified columns on the uploaded folders.
Graph cannot do this. Its fileSystemInfo facet is a separate client-supplied
record -- for files SharePoint surfaces it as the Modified column, but for
folders the library keeps its own value and ignores what Graph sends. The
SharePoint API does accept it, via a list item SystemUpdate, which is what
PnP gives us. SystemUpdate also avoids creating a new version and leaves
'Modified By' alone.
#>
param(
[string] $SiteUrl,
[string] $LibraryName,
[string] $BaseFolder,
[string] $SourceFolder,
$OrderedDirs,
[string] $ClientId
)
# Explicit parameter wins, then the environment, then the app registered for us.
$useClientId = $ClientId
if (-not $useClientId) { $useClientId = $env:PNPPOWERSHELL_CLIENTID }
if (-not $useClientId) { $useClientId = $script:DefaultClientId }
if (-not $useClientId) {
throw @"
Setting folder dates needs an Entra app (client) ID for your own tenant. App
registrations are tenant-specific, so this tool does not ship one.
Create one once (an administrator may need to run it):
Register-PnPEntraIDAppForInteractiveLogin ``
-ApplicationName 'OneNote Export' ``
-Tenant contoso.onmicrosoft.com ``
-SharePointDelegatePermissions AllSites.FullControl
It prints a client ID. Then either pass it each time with -ClientId, or set it
once so you never have to:
setx PNPPOWERSHELL_CLIENTID "<the id it printed>"
To upload without folder dates instead, add -SkipFolderDates.
"@
}
$connect = @{ Url = $SiteUrl; Interactive = $true; ErrorAction = 'Stop'; ClientId = $useClientId }
Write-Host ''
Write-Host 'Signing in to SharePoint to set folder dates...' -ForegroundColor Cyan
try {
Connect-PnPOnline @connect
}
catch {
throw @"
Could not sign in with PnP: $($_.Exception.Message)
Tried client ID: $useClientId
Folder dates need a SharePoint sign-in using an Entra app in this tenant. If that
app has been removed, an administrator can create a new one with:
Register-PnPEntraIDAppForInteractiveLogin ``
-ApplicationName 'OneNote Export' ``
-Tenant contoso.onmicrosoft.com ``
-SharePointDelegatePermissions AllSites.FullControl
then pass the client ID it prints as -ClientId.
To upload without touching folder dates, add -SkipFolderDates.
"@
}
# Ask SharePoint where the library actually lives rather than deriving it from a
# URL. The display name in -LibraryPath ('Documents') often differs from the URL
# segment ('Shared Documents'), and guessing that mapping is what breaks lookups.
try {
$list = Get-PnPList -Identity $LibraryName -Includes RootFolder -ErrorAction Stop
$libRoot = $list.RootFolder.ServerRelativeUrl.TrimEnd('/')
}
catch {
throw "Could not find a document library called '$LibraryName' on $SiteUrl -- $($_.Exception.Message)"
}
Write-Host " Library folder: $libRoot" -ForegroundColor DarkGray
# Under -WhatIf, prove the sign-in and path resolution work on a small sample
# instead of walking every folder read-only.
$work = $OrderedDirs
if ($WhatIfPreference) {
$work = @($OrderedDirs | Select-Object -First 5)
Write-Host " -WhatIf: checking the first $($work.Count) folder(s) only, writing nothing." -ForegroundColor Yellow
}
$stamped = 0; $missing = 0; $failed = 0; $n = 0
$verifySamples = New-Object System.Collections.ArrayList
try {
foreach ($dir in $work) {
$n++
$rel = $dir.FullName.Substring($SourceFolder.Length).TrimStart('\') -replace '\\', '/'
$segs = @()
if ($BaseFolder) { $segs += $BaseFolder }
$segs += $rel
$serverRel = $libRoot + '/' + ($segs -join '/')
if ($n -eq 1) { $script:LastTriedFolderUrl = $serverRel }
Write-Progress -Activity 'Setting folder dates' -Status "$n/$($work.Count) $rel" `
-PercentComplete ([int](100 * $n / [Math]::Max($work.Count, 1)))
try {
$folder = Get-PnPFolder -Url $serverRel -Includes ListItemAllFields -ErrorAction Stop
if ($WhatIfPreference) {
Write-Host (" would set {0:yyyy-MM-dd} / {1:yyyy-MM-dd} on {2}" -f `
$dir.CreationTimeUtc, $dir.LastWriteTimeUtc, $rel)
$stamped++
}
else {
$li = $folder.ListItemAllFields
$li['Created'] = $dir.CreationTimeUtc
$li['Modified'] = $dir.LastWriteTimeUtc
# UpdateOverwriteVersion, NOT SystemUpdate. SystemUpdate is
# documented to leave Modified / Modified By untouched, so it
# silently discards the dates we just set. This one writes them
# and still avoids creating a new version.
$li.UpdateOverwriteVersion()
Invoke-PnPQuery -ErrorAction Stop
$stamped++
if ($verifySamples.Count -lt 3) {
[void]$verifySamples.Add([pscustomobject]@{
Url = $serverRel; Expected = $dir.LastWriteTimeUtc; Rel = $rel
})
}
}
}
catch {
# A local folder with no files in it was never created remotely.
if ($_.Exception.Message -match '(?i)does not exist|not found|404') { $missing++ }
else {
$failed++
Write-Warning "FOLDER DATE FAILED: $rel -- $($_.Exception.Message)"
}
}
}
}
finally {
Write-Progress -Activity 'Setting folder dates' -Completed
try { Disconnect-PnPOnline -ErrorAction SilentlyContinue } catch { }
}
# Read a few back. Writing without error is not proof: SystemUpdate accepted the
# values and discarded them, which looked like success twice over.
if ($verifySamples.Count -gt 0 -and -not $WhatIfPreference) {
$verified = 0
foreach ($s in $verifySamples) {
try {
$f = Get-PnPFolder -Url $s.Url -Includes ListItemAllFields -ErrorAction Stop
$actual = $f.ListItemAllFields['Modified']
if ($actual -is [datetime] -and
[Math]::Abs(((([datetime]$actual).ToUniversalTime()) - $s.Expected).TotalMinutes) -le 60) {
$verified++
}
else {
Write-Host (" check: {0} -> SharePoint says {1}, expected {2}" -f `
$s.Rel, $actual, $s.Expected) -ForegroundColor Yellow
}
}
catch { }
}
if ($verified -eq 0) {
Write-Warning @"
Wrote $stamped folder date(s), but reading them back shows SharePoint did not keep
them. Overriding Created/Modified needs at least Manage Permissions (Full Control)
on the site -- check that the signed-in account has it.
"@
}
else {
Write-Host " verified $verified of $($verifySamples.Count) sampled folder(s)" -ForegroundColor DarkGray
}
}
# Every folder missing means the path is wrong, not that the tree is empty.
if ($stamped -eq 0 -and $missing -gt 0) {
Write-Warning @"
None of the $missing folder(s) were found in SharePoint, so no dates were set.
The first path tried was:
$($script:LastTriedFolderUrl)
Check that -LibraryPath points at the library the files were uploaded into.
"@
}
return [pscustomobject]@{ Stamped = $stamped; Missing = $missing; Failed = $failed }
}
#endregion
#region Main
# Values typed at the mandatory-parameter prompt are taken literally, quotes and
# all, so a pasted "quoted path" would never resolve. Strip stray quoting.
$SourceFolder = $SourceFolder.Trim().Trim('"').Trim("'")
$SiteUrl = $SiteUrl.Trim().Trim('"').Trim("'")
# Accept backslashes as well as forward slashes. On Windows people type
# 'md365\temp2' by reflex, and splitting only on '/' silently swallowed the
# subfolder, sending everything to the library root instead.
$LibraryPath = $LibraryPath.Trim().Trim('"').Trim("'") -replace '\\', '/'
$LibraryPath = ($LibraryPath -replace '/{2,}', '/').Trim('/')
if (-not (Test-Path -LiteralPath $SourceFolder -PathType Container)) {
throw "Source folder not found: $SourceFolder"
}
$SourceFolder = (Resolve-Path -LiteralPath $SourceFolder).Path
Write-Host ''
Write-Host 'Upload to SharePoint (metadata-preserving)' -ForegroundColor Cyan
Write-Host '------------------------------------------' -ForegroundColor Cyan
# The library display name and any subfolder beneath it, parsed without Graph so
# -FolderDatesOnly needs just the one SharePoint sign-in.
$pathSegments = @($LibraryPath -split '/' | Where-Object { $_ -ne '' })
$libraryName = $pathSegments[0]
$baseFolder = ''
if ($pathSegments.Count -gt 1) {
$baseFolder = ($pathSegments[1..($pathSegments.Count - 1)] -join '/')
}
if ($FolderDatesOnly) {
Write-Host 'Folder dates only: no files will be uploaded.' -ForegroundColor Yellow
$files = @()
}
else {
Connect-Graph
$target = Resolve-TargetDrive -SiteUrl $SiteUrl -LibraryPath $LibraryPath
$files = @(Get-ChildItem -LiteralPath $SourceFolder -Recurse -File)
Write-Host "Files : $($files.Count) under $SourceFolder"
}
Write-Host ''
$uploaded = 0; $skipped = 0; $failed = 0
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$done = 0
foreach ($file in $files) {
$done++
$rel = $file.FullName.Substring($SourceFolder.Length).TrimStart('\') -replace '\\', '/'
$remotePath = $rel
if ($target.BaseFolder) { $remotePath = "$($target.BaseFolder)/$rel" }
Write-Progress -Activity 'Uploading to SharePoint' -Status "$done/$($files.Count) $rel" `
-PercentComplete ([int](100 * $done / [Math]::Max($files.Count, 1)))
try {
# Skip files whose size and modified date already match (2s tolerance:
# SharePoint rounds fileSystemInfo to whole seconds).
if (-not $Force) {
$existing = Get-DriveItem -DriveBase $target.DriveBase -Path $remotePath
$remoteSize = Get-GraphProp $existing 'size'
if ($null -ne $remoteSize -and [long]$remoteSize -eq $file.Length) {
$remoteMod = Get-RemoteModifiedUtc $existing
if ($null -ne $remoteMod -and
[Math]::Abs(($remoteMod - $file.LastWriteTimeUtc).TotalSeconds) -le 2) {
$skipped++
continue
}
}
}
if ($PSCmdlet.ShouldProcess($remotePath, 'Upload')) {
$folder = ''
if ($remotePath.Contains('/')) {
$folder = $remotePath.Substring(0, $remotePath.LastIndexOf('/'))
}
Confirm-RemoteFolder -DriveBase $target.DriveBase -Path $folder
Send-FileToDrive -DriveBase $target.DriveBase -File $file -RemotePath $remotePath
$uploaded++
}
}
catch {
$failed++
Write-Warning "FAILED: $rel -- $($_.Exception.Message)"
}
}
Write-Progress -Activity 'Uploading to SharePoint' -Completed
# ---- Folder dates --------------------------------------------------------
# Runs last: uploading a file into a folder resets that folder's Modified date,
# so folders can only be stamped once nothing else will touch them. Deepest first
# for the same reason. Runs even when every file was skipped, so a re-run repairs
# folder dates from an earlier upload.
$dirs = @(Get-ChildItem -LiteralPath $SourceFolder -Recurse -Directory)
$ordered = @($dirs | Sort-Object { $_.FullName.Length } -Descending)
$dirsStamped = 0; $dirsMissing = 0; $dirsFailed = 0; $dirsSkipped = $false
$script:FolderDatesDelegated = $false
if ($ordered.Count -eq 0) { $dirsSkipped = $true }
elseif ($SkipFolderDates) {
$dirsSkipped = $true
Write-Host ''
Write-Host 'Skipping folder dates (-SkipFolderDates).' -ForegroundColor Yellow
}
elseif ($PSVersionTable.PSEdition -ne 'Core') {
# PnP.PowerShell 2.x/3.x is .NET Core only (its manifest requires 7.4.6 and
# CompatiblePSEditions = Core), so Windows PowerShell 5.1 cannot load it at all.
$pwsh = 'pwsh'
$found = Get-Command pwsh -ErrorAction SilentlyContinue
if ($found) { $pwsh = $found.Source }
$msg = @"
Folder dates need PnP.PowerShell, which only runs on PowerShell 7.
This window is Windows PowerShell $($PSVersionTable.PSVersion).
Re-run the same command with PowerShell 7:
"$pwsh" -File "$PSCommandPath" ...
(The OneNote exporter is the opposite: it needs Windows PowerShell 5.1, because
OneNote's COM interface will not work under 7. Only this uploader needs 7.)
Or add -SkipFolderDates to upload without them.
"@
if ($FolderDatesOnly) { throw $msg }
$dirsSkipped = $true
Write-Host ''
Write-Warning $msg
}
elseif (-not (Get-Module -ListAvailable -Name PnP.PowerShell)) {
$msg = @"
Folder dates need the PnP.PowerShell module, which is not installed for this
PowerShell. Install it once with:
Install-Module PnP.PowerShell -Scope CurrentUser
Or add -SkipFolderDates to upload without folder dates.
"@
if ($FolderDatesOnly) { throw $msg }
$dirsSkipped = $true
Write-Host ''
Write-Warning $msg
}
elseif ($FolderDatesOnly) {
# Nothing else ran in this process, so PnP has the field to itself.
Import-Module PnP.PowerShell -ErrorAction Stop
$r = Set-FolderDatesWithPnP -SiteUrl $SiteUrl -LibraryName $libraryName `
-BaseFolder $baseFolder -SourceFolder $SourceFolder `
-OrderedDirs $ordered -ClientId $ClientId
$dirsStamped = $r.Stamped; $dirsMissing = $r.Missing; $dirsFailed = $r.Failed
}
else {
# PnP and the Graph SDK ship different versions of Microsoft.Identity.Client
# (MSAL) -- 4.70 vs 4.82 -- and .NET loads only one per process. Whichever
# signs in first wins, and the other then fails with "Could not load type".
# The upload has already loaded Graph's copy here, so the folder dates run in
# a separate PowerShell that re-invokes this script in -FolderDatesOnly mode.
$pwshExe = (Get-Command pwsh -ErrorAction SilentlyContinue).Source
if (-not $pwshExe) {
$dirsSkipped = $true
Write-Host ''
Write-Warning @"
Folder dates need PowerShell 7 (pwsh), which was not found. Once installed, run:
pwsh -File "$PSCommandPath" -SourceFolder "$SourceFolder" ``
-SiteUrl "$SiteUrl" -LibraryPath "$LibraryPath" -FolderDatesOnly
"@
}
else {
Write-Host ''
Write-Host 'Setting folder dates in a separate PowerShell (MSAL conflict)...' -ForegroundColor Cyan
$childArgs = @(
'-NoProfile', '-File', $PSCommandPath,
'-SourceFolder', $SourceFolder,
'-SiteUrl', $SiteUrl,
'-LibraryPath', $LibraryPath,
'-FolderDatesOnly'
)
if ($ClientId) { $childArgs += @('-ClientId', $ClientId) }
& $pwshExe @childArgs
if ($LASTEXITCODE -ne 0) {
$dirsFailed = 1
Write-Warning "The folder-date step exited with code $LASTEXITCODE. Re-run it on its own with -FolderDatesOnly."
}
# The child prints its own summary; don't double-report its counts here.
$script:FolderDatesDelegated = $true
}
}
$sw.Stop()
Write-Host ''
Write-Host '-----------------------------------------------------------' -ForegroundColor Green
Write-Host ' Finished' -ForegroundColor Green
Write-Host '-----------------------------------------------------------' -ForegroundColor Green
Write-Host (' Uploaded {0}' -f $uploaded)
Write-Host (' Already up to date {0}' -f $skipped)
if ($script:FolderDatesDelegated) {
Write-Host ' Folder dates (reported separately above)'
}
else {
Write-Host (' Folder dates written {0}' -f $dirsStamped)
}
if ($failed -gt 0) {
Write-Host (' Failed {0} (see warnings above)' -f $failed) -ForegroundColor Red
}
if ($dirsFailed -gt 0) {
Write-Host (' Folder dates failed {0} (see warnings above)' -f $dirsFailed) -ForegroundColor Red
}
if ($dirsMissing -gt 0) {
Write-Host (' Empty folders skipped {0} (nothing in them to upload)' -f $dirsMissing) -ForegroundColor Yellow
}
if ($dirsSkipped -and $ordered.Count -gt 0 -and -not $script:FolderDatesDelegated) {
Write-Host ''
Write-Host ' Folder dates were not set, so folders will show the upload date.' -ForegroundColor Yellow
Write-Host ' File dates are unaffected and still show the real OneNote dates.' -ForegroundColor Yellow
}
Write-Host (' Time taken {0:hh\:mm\:ss}' -f $sw.Elapsed)
Write-Host ''
#endregion