-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCheck-ImageDownloads.ps1
More file actions
312 lines (266 loc) · 11.7 KB
/
Copy pathCheck-ImageDownloads.ps1
File metadata and controls
312 lines (266 loc) · 11.7 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
<#
.SYNOPSIS
Reports how many pictures in a OneNote notebook have actually been downloaded to
this computer, so you know when it is worth running the export.
.DESCRIPTION
OneNote keeps page text on your machine but fetches the pictures only when it
needs them. A picture that has not been downloaded comes back with no format,
and the exporter cannot save it -- that is what "could not be saved" means in
the export summary.
Ticking "Download all files and images" tells OneNote to fetch them all, but it
does that quietly in the background and never says when it has finished. This
script counts them so you can tell.
Run it -> see how many are still missing
Run it again -> see whether the number is going down
When it hits zero -> run the export
Use -Recheck after the first run to re-test only the pages that were missing
pictures, which is much faster than scanning everything again.
Use -Nudge to walk OneNote through those pages, which makes it fetch the
pictures on that page there and then. This is slower but does not rely on the
background download getting there on its own.
MUST run under Windows PowerShell 5.1, in a normal (non-Administrator) window --
same as Export-OneNoteMarkdown.ps1.
.PARAMETER Notebook
Notebook name. Omit to pick from a list.
.PARAMETER Recheck
Only re-test the pages that were short of pictures last time. Fast.
.PARAMETER Nudge
Open each page that is short of pictures so OneNote downloads them now.
.EXAMPLE
Right-click this file in File Explorer and choose "Run with PowerShell".
.EXAMPLE
powershell.exe -NoProfile -File .\Check-ImageDownloads.ps1 -Notebook "Sales Notebook" -Recheck
#>
[CmdletBinding()]
param(
[string] $Notebook,
[switch] $Recheck,
[switch] $Nudge,
[int] $NudgeWaitMs = 1500
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
$script:HS_PAGES = 4 # HierarchyScope.hsPages
$script:PI_BASIC = 0 # PageInfo.piBasic
$script:XS_CURRENT = 1
$script:InteractiveRun = -not $PSBoundParameters.ContainsKey('Notebook')
function Wait-ForUser {
if (-not $script:InteractiveRun) { return }
Write-Host ''
try { Read-Host 'Press Enter to close this window' | Out-Null } catch { }
}
trap {
Write-Host ''
Write-Host '-----------------------------------------------------------' -ForegroundColor Red
Write-Host ' Stopped before finishing.' -ForegroundColor Red
Write-Host '-----------------------------------------------------------' -ForegroundColor Red
Write-Host ''
Write-Host $_.Exception.Message -ForegroundColor Yellow
Wait-ForUser
exit 1
}
function Assert-Environment {
if ($PSVersionTable.PSVersion.Major -ne 5) {
throw @"
This must run under Windows PowerShell 5.1, not PowerShell $($PSVersionTable.PSVersion).
OneNote cannot be reached from 7.x.
Re-run with:
powershell.exe -NoProfile -File "$PSCommandPath"
"@
}
$principal = New-Object Security.Principal.WindowsPrincipal(
[Security.Principal.WindowsIdentity]::GetCurrent())
if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
throw @"
This window is running as Administrator. OneNote cannot be reached from an elevated
process. Close it and open a normal PowerShell window instead.
"@
}
}
function Get-OneNoteApp {
for ($attempt = 1; $attempt -le 4; $attempt++) {
try { return New-Object -ComObject OneNote.Application }
catch {
if ($attempt -eq 4) { throw "Could not attach to OneNote: $($_.Exception.Message)" }
Start-Sleep -Seconds ($attempt * 2)
}
}
}
function Get-Attr {
param($Node, [string] $Name, [string] $Default = '')
if ($null -eq $Node) { return $Default }
$a = $Node.Attributes.GetNamedItem($Name)
if ($null -eq $a) { return $Default }
return $a.Value
}
function Get-SafeName {
param([string] $Name)
$safe = $Name
foreach ($c in [System.IO.Path]::GetInvalidFileNameChars()) { $safe = $safe.Replace($c, '-') }
return ($safe -replace '\s+', '-')
}
# ---------------------------------------------------------------------------
Assert-Environment
Write-Host ''
Write-Host 'OneNote picture download check' -ForegroundColor Cyan
Write-Host '------------------------------' -ForegroundColor Cyan
$app = Get-OneNoteApp
[ref]$hierarchyXml = ''
$app.GetHierarchy('', $script:HS_PAGES, $hierarchyXml)
$hierarchy = [xml]$hierarchyXml.Value
$allNotebooks = @($hierarchy.SelectNodes("/*/*[local-name()='Notebook']"))
if ($allNotebooks.Count -eq 0) {
throw 'No notebooks are open in OneNote. Open the one you want to check, then run this again.'
}
$chosen = $null
if ($Notebook) {
$chosen = $allNotebooks | Where-Object { (Get-Attr $_ 'name') -eq $Notebook } | Select-Object -First 1
if (-not $chosen) {
$chosen = $allNotebooks | Where-Object { (Get-Attr $_ 'name') -like $Notebook } | Select-Object -First 1
}
if (-not $chosen) {
$names = ($allNotebooks | ForEach-Object { ' - ' + (Get-Attr $_ 'name') }) -join "`r`n"
throw "No notebook called '$Notebook'. Open notebooks are:`r`n$names"
}
}
else {
Write-Host ''
Write-Host 'Which notebook do you want to check?' -ForegroundColor Green
Write-Host ''
for ($i = 0; $i -lt $allNotebooks.Count; $i++) {
Write-Host (' {0,2}. {1}' -f ($i + 1), (Get-Attr $allNotebooks[$i] 'name'))
}
Write-Host ''
while ($null -eq $chosen) {
$answer = Read-Host "Type a number from 1 to $($allNotebooks.Count) and press Enter"
if ($answer -match '^\s*(\d+)\s*$') {
$pick = [int]$Matches[1]
if ($pick -ge 1 -and $pick -le $allNotebooks.Count) { $chosen = $allNotebooks[$pick - 1] }
}
if ($null -eq $chosen) { Write-Host " '$answer' is not one of the numbers above." -ForegroundColor Yellow }
}
}
$nbName = Get-Attr $chosen 'name' 'Notebook'
Write-Host ''
Write-Host "Checking: $nbName" -ForegroundColor Green
$stateFile = Join-Path $PSScriptRoot ("_image-status-{0}.json" -f (Get-SafeName $nbName))
# Which pages to test: everything, or just the ones that were short last time.
$pages = @($chosen.SelectNodes(".//*[local-name()='Page']"))
$pageById = @{}
foreach ($p in $pages) { $pageById[(Get-Attr $p 'ID')] = $p }
$targets = $pages
if ($Recheck) {
if (-not (Test-Path -LiteralPath $stateFile)) {
Write-Host ''
Write-Host 'No previous check found, so this run will scan everything.' -ForegroundColor Yellow
}
else {
$prior = Get-Content -LiteralPath $stateFile -Raw | ConvertFrom-Json
$priorIds = @($prior.PendingPageIds)
$targets = @($priorIds | ForEach-Object { $pageById[$_] } | Where-Object { $_ })
if ($targets.Count -eq 0) {
Write-Host ''
Write-Host '-----------------------------------------------------------' -ForegroundColor Green
Write-Host ' Nothing left to re-check.' -ForegroundColor Green
Write-Host '-----------------------------------------------------------' -ForegroundColor Green
Write-Host ''
Write-Host " Every picture in $nbName was already downloaded at the last" -ForegroundColor Green
Write-Host " full check ($($prior.Ready) of $($prior.TotalImages)). Run the export." -ForegroundColor Green
Write-Host ''
Write-Host ' To scan the whole notebook again, run without -Recheck.'
Wait-ForUser
exit 0
}
Write-Host ''
Write-Host "Re-checking only the $($targets.Count) page(s) that were short of pictures last time." -ForegroundColor Cyan
}
}
Write-Host ''
Write-Host "$($targets.Count) page(s) to look at. Please leave OneNote alone while this runs." -ForegroundColor Yellow
if (-not $Recheck -and $targets.Count -gt 800) {
Write-Host ("Roughly {0:n0} minute(s) for a full check. Use -Recheck next time for a quick one." -f `
[Math]::Ceiling($targets.Count * 0.12 / 60)) -ForegroundColor Yellow
}
Write-Host ''
$totalImages = 0
$ready = 0
$pendingIds = New-Object System.Collections.ArrayList
$bySection = @{}
$n = 0
$sw = [System.Diagnostics.Stopwatch]::StartNew()
foreach ($pg in $targets) {
$n++
$pageId = Get-Attr $pg 'ID'
$title = Get-Attr $pg 'name' 'Untitled'
$secName = 'Unknown section'
if ($pg.ParentNode) { $secName = Get-Attr $pg.ParentNode 'name' 'Unknown section' }
if ($n % 5 -eq 0 -or $n -eq $targets.Count) {
$eta = ''
if ($n -gt 20) {
$per = $sw.Elapsed.TotalSeconds / $n
$eta = ' | about {0:hh\:mm\:ss} left' -f [TimeSpan]::FromSeconds($per * ($targets.Count - $n))
}
Write-Progress -Activity 'Checking pictures' -Status "$n/$($targets.Count)$eta" `
-CurrentOperation $title -PercentComplete ([int](100 * $n / [Math]::Max($targets.Count, 1)))
}
if ($Nudge) {
try { $app.NavigateTo($pageId, '', $false); Start-Sleep -Milliseconds $NudgeWaitMs } catch { }
}
[ref]$raw = ''
try { $app.GetPageContent($pageId, $raw, $script:PI_BASIC, $script:XS_CURRENT) } catch { continue }
$doc = [xml]$raw.Value
$pagePending = 0
foreach ($img in $doc.SelectNodes("//*[local-name()='Image']")) {
$totalImages++
# An image OneNote has not fetched yet reports no format, and its bytes
# cannot be read (GetBinaryPageContent fails with 0x8004200F).
if ([string]::IsNullOrWhiteSpace((Get-Attr $img 'format'))) { $pagePending++ }
else { $ready++ }
}
if ($pagePending -gt 0) {
[void]$pendingIds.Add($pageId)
if (-not $bySection.ContainsKey($secName)) { $bySection[$secName] = 0 }
$bySection[$secName] += $pagePending
}
if ($n % 250 -eq 0) { [GC]::Collect() }
}
Write-Progress -Activity 'Checking pictures' -Completed
$sw.Stop()
$pending = $totalImages - $ready
# Keep the page list so -Recheck can be quick next time.
@{
Notebook = $nbName
CheckedUtc = (Get-Date).ToUniversalTime().ToString('o')
TotalImages = $totalImages
Ready = $ready
Pending = $pending
PendingPageIds = @($pendingIds)
} | ConvertTo-Json -Depth 3 | Set-Content -LiteralPath $stateFile -Encoding UTF8
Write-Host ''
Write-Host '-----------------------------------------------------------' -ForegroundColor Green
Write-Host ' Result' -ForegroundColor Green
Write-Host '-----------------------------------------------------------' -ForegroundColor Green
Write-Host ''
Write-Host (' Pictures found {0:n0}' -f $totalImages)
Write-Host (' Downloaded, ready {0:n0}' -f $ready)
Write-Host (' Still missing {0:n0}' -f $pending)
if ($totalImages -gt 0) {
Write-Host (' Complete {0:n1}%' -f (100 * $ready / $totalImages))
}
Write-Host (' Time taken {0:hh\:mm\:ss}' -f $sw.Elapsed)
Write-Host ''
if ($pending -eq 0 -and $totalImages -gt 0) {
Write-Host ' All pictures are downloaded. Run the export now.' -ForegroundColor Green
}
elseif ($pending -gt 0) {
Write-Host ' Sections still waiting on pictures:' -ForegroundColor Yellow
$bySection.GetEnumerator() | Sort-Object Value -Descending | Select-Object -First 8 |
ForEach-Object { Write-Host (' {0,6:n0} {1}' -f $_.Value, $_.Key) -ForegroundColor Yellow }
Write-Host ''
Write-Host ' Leave OneNote open and connected, then check again with:' -ForegroundColor Yellow
Write-Host (" powershell.exe -NoProfile -File `"$PSCommandPath`" -Notebook `"$nbName`" -Recheck") -ForegroundColor Yellow
Write-Host ''
Write-Host ' If the number is not going down, make OneNote fetch them directly:' -ForegroundColor Yellow
Write-Host (" powershell.exe -NoProfile -File `"$PSCommandPath`" -Notebook `"$nbName`" -Recheck -Nudge") -ForegroundColor Yellow
}
Wait-ForUser