forked from SjoerdV/ConvertOneNote2MarkDown
-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathConvertOneNote2MarkDown-v2.ps1
1474 lines (1365 loc) · 70.6 KB
/
ConvertOneNote2MarkDown-v2.ps1
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()]
param (
[Parameter()]
[string]
$ConversionConfigurationExportPath
,
[Parameter()]
[switch]
$Exit
)
Function Validate-Dependencies {
[CmdletBinding()]
param ()
# Validate Powershell versions. Supported version are between 5.x (possibly lower) and 7.0.x
if ($PSVersionTable.PSVersion -ge [version]'7.1') {
throw "Unsupported Powershell version $( $PSVersionTable.PSVersion ), because it does not support importing Win32 GAC Assemblies. Supported versions are between Powershell 5.x and 7.0.x. See README.md for instructions to install Powershell 7.0.x"
}
# Validate assemblies
if ( ($env:OS -imatch 'Windows') -and ! (Get-Item -Path $env:windir\assembly\GAC_MSIL\*onenote*) ) {
"There are missing onenote assemblies. Please ensure the Desktop version of Onenote 2016 or above is installed." | Write-Warning
}
# Validate dependencies
if (! (Get-Command -Name 'pandoc.exe' -ErrorAction SilentlyContinue) ) {
throw "Could not locate pandoc.exe. Please ensure pandoc is installed for all users, and available in PATH. If pandoc was just installed using .msi or chocolatey, you may need to restart Powershell or the computer for pandoc to be set correctly in PATH."
}
}
Function Get-DefaultConfiguration {
[CmdletBinding()]
param ()
# The default configuration
$config = [ordered]@{
dryRun = @{
description = @'
Whether to do a dry run
0: Convert - Default
1: Dry run
'@
default = 0
value = 0
validateRange = 0,1
}
notesdestpath = @{
description = @'
Specify folder path that will contain your resulting Notes structure - Default: c:\temp\notes
'@
default = 'c:\temp\notes'
value = 'c:\temp\notes'
validateOptions = 'directoryexists'
}
targetNotebook = @{
description = @'
Specify a notebook name to convert
'': Convert all notebooks - Default
'mynotebook': Convert specific notebook named 'mynotebook'
'@
default = ''
value = ''
}
usedocx = @{
description = @'
Whether to create new word .docx or reuse existing ones
1: Always create new .docx files - Default
2: Use existing .docx files (90% faster)
'@
default = 1
value = 1
validateRange = 1,2
}
keepdocx = @{
description = @'
Whether to discard word .docx after conversion
1: Discard intermediate .docx files - Default
2: Keep .docx files
'@
default = 1
value = 1
validateRange = 1,2
}
docxNamingConvention = @{
description = @'
Whether to use name .docx files using page ID with last modified date epoch, or hierarchy
1: Use page ID with last modified date epoch (recommended if you chose to use existing .docx files) - Default
2: Use hierarchy
'@
default = 1
value = 1
validateRange = 1,2
}
prefixFolders = @{
description = @'
Whether to use prefix vs subfolders
1: Create folders for subpages (e.g. Page\Subpage.md) - Default
2: Add prefixes for subpages (e.g. Page_Subpage.md)
'@
default = 1
value = 1
validateRange = 1,2
}
mdFileNameAndFolderNameMaxLength = @{
description = @'
Specify a value between 32 and 255 as the maximum length of markdown file names, and their folder names (only when using subfolders for subpages (e.g. Page\Subpage.md)). File and folder names with length exceeding this value will be truncated accordingly.
NOTE: If you are using prefixes for subpages (e.g. Page_Subpage.md), it is recommended to set this to at 100 or more.
Default: 32
'@
default = 32
value = 32
validateRange = 32,255
}
medialocation = @{
description = @'
Whether to store media in single or multiple folders
1: Images stored in single 'media' folder at Notebook-level - Default
2: Separate 'media' folder for each folder in the hierarchy
'@
default = 1
value = 1
validateRange = 1,2
}
conversion = @{
description = @'
Specify Pandoc output format and optional extension(s) in the format: <markdownformat><+extension><-extension>
Use this to customize the markdown flavor
Extension(s) must be supported by your pandoc version. See: https://pandoc.org/MANUAL.html#options
Examples:
markdown-simple_tables-multiline_tables-grid_tables+pipe_tables
commonmark+pipe_tables
gfm+pipe_tables
markdown_mmd-simple_tables-multiline_tables-grid_tables+pipe_tables
markdown_phpextra-simple_tables-multiline_tables-grid_tables+pipe_tables
markdown_strict+simple_tables-multiline_tables-grid_tables+pipe_tables
Default:
markdown-simple_tables-multiline_tables-grid_tables+pipe_tables
'@
default = 'markdown-simple_tables-multiline_tables-grid_tables+pipe_tables'
value = 'markdown-simple_tables-multiline_tables-grid_tables+pipe_tables'
}
headerTimestampEnabled = @{
description = @'
Whether to include page timestamp and separator at top of document
1: Include - Default
2: Don't include
'@
default = 1
value = 1
validateRange = 1,2
}
keepspaces = @{
description = @'
Whether to clear extra newlines between unordered (bullet) and ordered (numbered) list items, non-breaking spaces from blank lines, and `>` after unordered lists
1: Clear - Default
2: Don't clear
'@
default = 1
value = 1
validateRange = 1,2
}
keepescape = @{
description = @'
Whether to clear escape symbols from md files. See: https://pandoc.org/MANUAL.html#backslash-escapes
1: Clear all '\' characters - Default
2: Clear all '\' characters except those preceding alphanumeric characters
3: Keep '\' symbol escape
'@
default = 1
value = 1
validateRange = 1,3
}
newlineCharacter = @{
description = @'
Whether to use Line Feed (LF) or Carriage Return + Line Feed (CRLF) for new lines
1: LF (unix) - Default
2: CRLF (windows)
'@
default = 1
value = 1
validateRange = 1,2
}
exportPdf = @{
description = @'
Whether to include a PDF export alongside the markdown file
1: Don't include PDF - Default
2: Include PDF
'@
default = 1
value = 1
validateRange = 1,2
}
}
$config
}
Function New-ConfigurationFile {
[CmdletBinding()]
param ()
# Generate a configuration file config.example.ps1
@'
#
# Note: This config file is for those who are lazy to type in configuration everytime you run ./ConvertOneNote2MarkDown-v2.ps1
#
# Steps:
# 1) Rename this file to config.ps1. Ensure it is in the same folder as the ConvertOneNote2MarkDown-v2.ps1 script
# 2) Configure the options below to your liking
# 3) Run the main script: ./ConvertOneNote2MarkDown-v2.ps1. Sit back while the script starts converting immediately.
'@ | Out-File "$PSScriptRoot/config.example.ps1" -Encoding utf8
$defaultConfig = Get-DefaultConfiguration
foreach ($key in $defaultConfig.Keys) {
# Add a '#' in front of each line of the option description
$defaultConfig[$key]['description'].Trim() -replace "^|`n", "`n# " | Out-File "$PSScriptRoot/config.example.ps1" -Encoding utf8 -Append
# Write the variable
if ( $defaultConfig[$key]['default'] -is [string]) {
"`$$key = '$( $defaultConfig[$key]['default'] )'" | Out-File "$PSScriptRoot/config.example.ps1" -Encoding utf8 -Append
}else {
"`$$key = $( $defaultConfig[$key]['default'] )" | Out-File "$PSScriptRoot/config.example.ps1" -Encoding utf8 -Append
}
}
}
Function Compile-Configuration {
[CmdletBinding()]
param ()
# Get a default configuration
$config = Get-DefaultConfiguration
# Override configuration
$configFile = [io.path]::combine( $PSScriptRoot, 'config.ps1' )
if (Test-Path $configFile) {
try {
& {
$scriptblock = [scriptblock]::Create( (Get-Content -LiteralPath $configFile -Raw) )
. $scriptblock *>$null # Cleanup the pipeline
foreach ($key in @($config.Keys)) {
# E.g. 'string', 'int'
$typeName = [Microsoft.PowerShell.ToStringCodeMethods]::Type($config[$key]['default'].GetType())
$config[$key]['value'] = Invoke-Expression -Command "(Get-Variable -Name `$key -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Value) -as [$typeName]"
if ($config[$key]['value'] -is [string]) {
# Trim string
$config[$key]['value'] = $config[$key]['value'].Trim()
# Remove trailing slash(es) for paths
if ($key -match 'path' -and $config[$key]['value'] -match '[/\\]') {
$config[$key]['value'] = $config[$key]['value'].TrimEnd('/').TrimEnd('\')
}
}
# Fallback on default value if the input is empty string
if ($config[$key]['value'] -is [string] -and $config[$key]['value'] -eq '') {
$config[$key]['value'] = $config[$key]['default']
}
# Fallback on default value if the input is empty integer (0)
if ($config[$key]['value'] -is [int] -and $config[$key]['value'] -eq 0) {
$config[$key]['value'] = $config[$key]['default']
}
}
}
}catch {
Write-Warning "There is an error in the configuration file $configFile $( $_.ScriptStackTrace ). `nThe exception was: $( $_.Exception.Message )"
throw
}
}else {
# Get override configuration from interactive prompts
foreach ($key in $config.Keys) {
"" | Write-Host -ForegroundColor Cyan
$config[$key]['description'] | Write-Host -ForegroundColor Cyan
# E.g. 'string', 'int'
$typeName = [Microsoft.PowerShell.ToStringCodeMethods]::Type($config[$key]['default'].GetType())
# Keep prompting until we get a answer of castable type
do {
# Cast the input as a type. E.g. Read-Host -Prompt 'Entry' -as [int]
$config[$key]['value'] = Invoke-Expression -Command "(Read-Host -Prompt 'Entry') -as [$typeName]"
}while ($null -eq $config[$key]['value'])
# Fallback on default value if the input is empty string
if ($config[$key]['value'] -is [string] -and $config[$key]['value'] -eq '') {
$config[$key]['value'] = $config[$key]['default']
}
# Fallback on default value if the input is empty integer (0)
if ($config[$key]['value'] -is [int] -and $config[$key]['value'] -eq 0) {
$config[$key]['value'] = $config[$key]['default']
}
}
}
$config
}
Function Validate-Configuration {
[CmdletBinding(DefaultParameterSetName='default')]
param (
[Parameter(ParameterSetName='default',Position=0)]
[object]
$Config
,
[Parameter(ParameterSetName='pipeline',ValueFromPipeline)]
[object]
$InputObject
)
process {
if ($InputObject) {
$Config = $InputObject
}
if ($null -eq $Config) {
throw "No input parameters specified."
}
# Validate a given configuration against a prototype configuration
$defaultConfig = Get-DefaultConfiguration
foreach ($key in $defaultConfig.Keys) {
if (! $Config.Contains($key) -or ($null -eq $Config[$key]) -or ($null -eq $Config[$key]['value'])) {
throw "Missing or invalid configuration option '$key'. Expected a value of type $( $defaultConfig[$key]['default'].GetType().FullName )"
}
if ($defaultConfig[$key]['default'].GetType().FullName -ne $Config[$key]['value'].GetType().FullName) {
throw "Invalid configuration option '$key'. Expected a value of type $( $defaultConfig[$key]['default'].GetType().FullName ), but value was of type $( $config[$key]['value'].GetType().FullName )"
}
if ($defaultConfig[$key].Contains('validateOptions')) {
if ($defaultConfig[$key]['validateOptions'] -contains 'directoryexists') {
if ( ! $config[$key]['value'] -or ! (Test-Path $config[$key]['value'] -PathType Container -ErrorAction SilentlyContinue) ) {
throw "Invalid configuration option '$key'. The directory '$( $config[$key]['value'] )' does not exist, or is a file"
}
}
}
if ($defaultConfig[$key].Contains('validateRange')) {
if ($Config[$key]['value'] -lt $defaultConfig[$key]['validateRange'][0] -or $Config[$key]['value'] -gt $defaultConfig[$key]['validateRange'][1]) {
throw "Invalid configuration option '$key'. The value must be between $( $defaultConfig[$key]['validateRange'][0] ) and $( $defaultConfig[$key]['validateRange'][1] )"
}
}
}
# Warn of unknown configuration options
foreach ($key in $config.Keys) {
if (! $defaultConfig.Contains($key)) {
"Unknown configuration option '$key'" | Write-Warning
}
}
$Config
}
}
Function Print-Configuration {
[CmdletBinding(DefaultParameterSetName='default')]
param (
[Parameter(ParameterSetName='default',Position=0)]
[object]
$Config
,
[Parameter(ParameterSetName='pipeline',ValueFromPipeline)]
[object]
$InputObject
)
process {
if ($InputObject) {
$Config = $InputObject
}
if ($null -eq $Config) {
throw "No input parameters specified."
}
foreach ($key in $Config.Keys) {
"$( $key ): $( $Config[$key]['value'] )" | Write-Host -ForegroundColor DarkGray
}
}
}
Function Truncate-PathFileName {
[CmdletBinding(DefaultParameterSetName='default')]
param (
[Parameter(ParameterSetName='default',Position=0)]
[ValidateNotNullOrEmpty()]
[string]
$Path
,
[Parameter(ParameterSetName='pipeline',ValueFromPipeline)]
[string]
$InputObject
,
[Parameter()]
[ValidateRange(0,255)]
[int]
$Length
)
process {
if ($InputObject) {
$Path = $InputObject
}
if ($null -eq $Path) {
throw "No input parameters specified."
}
$maxLength = 255
if ($Length) {
$maxLength = $Length
}
# On Windows, even with support for long absolute file paths, there's still a limit for file or folder names (i.e. File or folder name limit: Max 255 characters long)
$name = Split-Path $Path -Leaf
if ($name.Length -gt $maxLength) {
$parent = Split-Path $Path -Parent
$truncatedName = $name.Substring(0, $maxLength)
[io.path]::combine( $parent, $truncatedName )
}else {
$Path
}
}
}
Function Remove-InvalidFileNameChars {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline = $true)]
[AllowEmptyString()]
[string]$Name
,
[switch]$KeepPathSpaces
)
# Remove boundary whitespaces. So we don't get trailing dashes
$Name = $Name.Trim()
$newName = $Name.Split([IO.Path]::GetInvalidFileNameChars()) -join '-'
$newName = $newName -replace "\[", "("
$newName = $newName -replace "\]", ")"
$newName = if ($KeepPathSpaces) {
$newName -replace "\s", " "
} else {
$newName -replace "\s", "-"
}
return $newName
}
Function Remove-InvalidFileNameCharsInsertedFiles {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline = $true,ValueFromPipelineByPropertyName = $true)]
[AllowEmptyString()]
[string]$Name
,
[string]$Replacement = ""
,
[string]$SpecialChars = "#$%^*[]'<>!@{};"
,
[switch]$KeepPathSpaces
)
# Remove boundary whitespaces. So we don't get trailing dashes
$Name = $Name.Trim()
$rePattern = ($SpecialChars.ToCharArray() | ForEach-Object { [regex]::Escape($_) }) -join "|"
$newName = $Name.Split([IO.Path]::GetInvalidFileNameChars()) -join '-'
$newName = $newName -replace $rePattern, ""
$newName = if ($KeepPathSpaces) {
$newName -replace "\s", " "
} else {
$newName -replace "\s", "-"
}
return $newName
}
Function Encode-Markdown {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline = $true,ValueFromPipelineByPropertyName = $true)]
[AllowEmptyString()]
[string]
$Name
,
[Parameter()]
[switch]
$Uri
)
if ($Uri) {
$markdownChars = '[]()'.ToCharArray()
foreach ($c in $markdownChars) {
$Name = $Name.Replace("$c", "\$c")
}
}else {
# See: https://pandoc.org/MANUAL.html#backslash-escapes
$markdownChars = '\*_{}[]()#+-.!'.ToCharArray()
foreach ($c in $markdownChars) {
$Name = $Name.Replace("$c", "\$c")
}
$markdownChars2 = '`'
foreach ($c in $markdownChars2) {
$Name = $Name.Replace("$c", "$c$c$c")
}
}
$Name
}
Function Set-ContentNoBom {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline = $true,ValueFromPipelineByPropertyName = $true)]
[AllowEmptyString()]
[string]
$LiteralPath
,
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[array]
$Value
)
process {
if ($PSVersionTable.PSVersion.Major -le 5) {
try {
$content = $Value -join ''
[IO.File]::WriteAllLines($LiteralPath, $content)
}catch {
if ($ErrorActionPreference -eq 'Stop') {
throw
}else {
Write-Error -ErrorRecord $_
}
}
}else {
Set-Content @PSBoundParameters
}
}
}
Function New-OneNoteConnection {
[CmdletBinding()]
param ()
# Create a OneNote connection. See: https://docs.microsoft.com/en-us/office/client-developer/onenote/application-interface-onenote
if ($PSVersionTable.PSVersion.Major -le 5) {
if ($OneNote = New-Object -ComObject OneNote.Application) {
$OneNote
}else {
Write-Error "Failed to make connection to OneNote." -ErrorAction Continue
throw
}
}else {
# Works between powershell 5.x (possibly lower) and 7.0, but not >= 7.1. 7.1 and above doesn't seem to support loading Win32 GAC Assemblies.
if (Add-Type -Path $env:windir\assembly\GAC_MSIL\Microsoft.Office.Interop.OneNote\15.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.OneNote.dll -PassThru) {
$OneNote = [Microsoft.Office.Interop.OneNote.ApplicationClass]::new()
$OneNote
}else {
Write-Error "Failed to make connection to OneNote." -ErrorAction Continue
throw
}
}
}
Function Remove-OneNoteConnection {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[object]
$OneNoteConnection
)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($OneNoteConnection) | Out-Null
}
Function Get-OneNoteHierarchy {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[object]
$OneNoteConnection
)
# Open OneNote hierarchy
[xml]$hierarchy = ""
$OneNoteConnection.GetHierarchy("", [Microsoft.Office.InterOp.OneNote.HierarchyScope]::hsPages, [ref]$hierarchy)
$hierarchy
}
Function Get-OneNotePageContent {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[object]
$OneNoteConnection
,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]
$PageId
)
# Get page's xml content
[xml]$page = ""
$OneNoteConnection.GetPageContent($PageId, [ref]$page, 7)
$page
}
Function Publish-OneNotePage {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[object]
$OneNoteConnection
,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]
$PageId
,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]
$Destination
,
[Parameter(Mandatory)]
[ValidateSet('pfOneNotePackage', 'pfOneNotePackage', 'pfOneNote ', 'pfPDF', 'pfXPS', 'pfWord', 'pfEMF', 'pfHTML', 'pfOneNote2007')]
[ValidateNotNullOrEmpty()]
[string]
$PublishFormat
)
$OneNoteConnection.Publish($PageId, $Destination, $PublishFormat, "")
}
Function New-SectionGroupConversionConfig {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[object]
$OneNoteConnection
,
# The desired directory to store any converted Page(s) found in this Section Group's Section(s)
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]
$NotesDestination
,
[Parameter(Mandatory)]
[object]
$Config
,
# Section Group XML object(s)
[Parameter(Mandatory)]
[array]
$SectionGroups
,
[Parameter(Mandatory)]
[int]
$LevelsFromRoot
,
[Parameter()]
[switch]
$AsArray
)
$sectionGroupConversionConfig = [System.Collections.ArrayList]@()
# Build an object representing the conversion of a Section Group (treat a Notebook as a Section Group, it is no different)
foreach ($sectionGroup in $SectionGroups) {
# Skip over Section Groups in recycle bin
if ((Get-Member -InputObject $sectionGroup -Name 'isRecycleBin') -and $sectionGroup.isRecycleBin -eq 'true') {
continue
}
$cfg = [ordered]@{}
if ($LevelsFromRoot -eq 0) {
"`nBuilding conversion configuration for $( $sectionGroup.name ) [Notebook]" | Write-Host -ForegroundColor DarkGreen
}else {
"`n$( '#' * ($LevelsFromRoot) ) Building conversion configuration for $( $sectionGroup.name ) [Section Group]" | Write-Host -ForegroundColor DarkGray
}
# Build this Section Group
$cfg = [ordered]@{}
$cfg['object'] = $sectionGroup # Keep a reference to the SectionGroup object
$cfg['kind'] = 'SectionGroup'
$cfg['id'] = $sectionGroup.ID # E.g. {9570CCF6-17C2-4DCE-83A0-F58AE8914E29}{1}{B0}
$cfg['nameCompat'] = $sectionGroup.name | Remove-InvalidFileNameChars
$cfg['levelsFromRoot'] = $LevelsFromRoot
$cfg['uri'] = $sectionGroup.path # E.g. https://d.docs.live.net/0123456789abcdef/Skydrive Notebooks/mynotebook/mysectiongroup
$cfg['notesDirectory'] = [io.path]::combine( $NotesDestination.TrimEnd('/').TrimEnd('\').Replace('\', [io.path]::DirectorySeparatorChar), $cfg['nameCompat'] ) # No need to truncate. Section Group and Section names have a max length of 50, so we should never hit the absolute path, file name, or directory name limits on Windows
$cfg['notesBaseDirectory'] = & {
# E.g. 'c:\temp\notes\mynotebook\mysectiongroup'
# E.g. levelsFromRoot: 1
$split = $cfg['notesDirectory'].Split( [io.path]::DirectorySeparatorChar )
# E.g. 5
$totalLevels = $split.Count
# E.g. 0..(5-1-1) -> 'c:\temp\notes\mynotebook'
$split[0..($totalLevels - $cfg['levelsFromRoot'] - 1)] -join [io.path]::DirectorySeparatorChar
}
$cfg['notebookName'] = Split-Path $cfg['notesBaseDirectory'] -Leaf
$cfg['pathFromRoot'] = $cfg['notesDirectory'].Replace($cfg['notesBaseDirectory'], '').Trim([io.path]::DirectorySeparatorChar)
$cfg['pathFromRootCompat'] = $cfg['pathFromRoot'] | Remove-InvalidFileNameChars
$cfg['notesDocxDirectory'] = [io.path]::combine( $cfg['notesBaseDirectory'], 'docx' )
$cfg['directoriesToCreate'] = @()
# Build this Section Group's sections
$cfg['sections'] = [System.Collections.ArrayList]@()
if (! (Get-Member -InputObject $sectionGroup -Name 'Section') -and ! (Get-Member -InputObject $sectionGroup -Name 'SectionGroup') ) {
"Ignoring empty Section Group: $( $cfg['pathFromRoot'] )" | Write-Host -ForegroundColor DarkGray
}
if (Get-Member -InputObject $sectionGroup -Name 'Section') {
foreach ($section in $sectionGroup.Section) {
"$( '#' * ($LevelsFromRoot + 1) ) Building conversion configuration for $( $section.name ) [Section]" | Write-Host -ForegroundColor DarkGray
$sectionCfg = [ordered]@{}
$sectionCfg['notebookName'] = $cfg['notebookName']
$sectionCfg['notesBaseDirectory'] = $cfg['notesBaseDirectory']
$sectionCfg['notesDirectory'] = $cfg['notesDirectory']
$sectionCfg['sectionGroupUri'] = $cfg['uri'] # Keep a reference to my Section Group Configuration object's uri
$sectionCfg['sectionGroupName'] = $cfg['object'].name
$sectionCfg['object'] = $section # Keep a reference to the Section object
$sectionCfg['kind'] = 'Section'
$sectionCfg['id'] = $section.ID # E.g {BE566C4F-73DC-43BD-AE7A-1954F8B22C2A}{1}{B0}
$sectionCfg['nameCompat'] = $section.name | Remove-InvalidFileNameChars
$sectionCfg['levelsFromRoot'] = $cfg['levelsFromRoot'] + 1
$sectionCfg['pathFromRoot'] = "$( $cfg['pathFromRoot'] )$( [io.path]::DirectorySeparatorChar )$( $sectionCfg['nameCompat'] )".Trim([io.path]::DirectorySeparatorChar) # No need to truncate. Section Group and Section names have a max length of 50, so we should never hit the absolute path, file name, or directory name limits on Windows
$sectionCfg['pathFromRootCompat'] = $sectionCfg['pathFromRoot'] | Remove-InvalidFileNameChars
$sectionCfg['uri'] = $section.path # E.g. https://d.docs.live.net/0123456789abcdef/Skydrive Notebooks/mynotebook/mysectiongroup/mysection
$sectionCfg['lastModifiedTime'] = [Datetime]::ParseExact($section.lastModifiedTime, 'yyyy-MM-ddTHH:mm:ss.fffZ', $null)
$sectionCfg['lastModifiedTimeEpoch'] = [int][double]::Parse((Get-Date ((Get-Date $sectionCfg['lastModifiedTime']).ToUniversalTime()) -UFormat %s)) # Epoch
$sectionCfg['pages'] = [System.Collections.ArrayList]@()
# Build Section's pages
if (Get-Member -InputObject $section -Name 'Page') {
foreach ($page in $section.Page) {
"$( '#' * ($LevelsFromRoot + 2) ) Building conversion configuration for $( $page.name ) [Page]" | Write-Host -ForegroundColor DarkGray
$previousPage = if ($sectionCfg['pages'].Count -gt 0) { $sectionCfg['pages'][$sectionCfg['pages'].Count - 1] } else { $null }
$pageCfg = [ordered]@{}
$pageCfg['notebookName'] = $cfg['notebookName']
$pageCfg['notesBaseDirectory'] = $cfg['notesBaseDirectory']
$pageCfg['notesDirectory'] = $cfg['notesDirectory']
$pageCfg['sectionGroupUri'] = $cfg['uri'] # Keep a reference to mt Section Group Configuration object's uri
$pageCfg['sectionGroupName'] = $cfg['object'].name
$pageCfg['sectionUri'] = $sectionCfg['uri'] # Keep a reference to my Section Configuration object's uri
$pageCfg['sectionName'] = $sectionCfg['object'].name
$pageCfg['object'] = $page # Keep a reference to my Page object
$pageCfg['kind'] = 'Page'
$pageCfg['id'] = $page.ID # E.g. {3D017C7D-F890-4AC8-A094-DEC1163E7B85}{1}{E19461971475288592555920101886406896686096991}
$pageCfg['nameCompat'] = $page.name | Remove-InvalidFileNameChars
$pageCfg['levelsFromRoot'] = $sectionCfg['levelsFromRoot']
$pageCfg['pathFromRoot'] = "$( $sectionCfg['pathFromRoot'] )$( [io.path]::DirectorySeparatorChar )$( $pageCfg['nameCompat'] )"
$pageCfg['pathFromRootCompat'] = $pageCfg['pathFromRoot'] | Remove-InvalidFileNameChars
$pageCfg['uri'] = "$( $sectionCfg['object'].path )/$( $page.name )" # There's no $page.path property, so we generate one. E.g. https://d.docs.live.net/0123456789abcdef/Skydrive Notebooks/mynotebook/mysectiongroup/mysection/mypage
$pageCfg['dateTime'] = [Datetime]::ParseExact($page.dateTime, 'yyyy-MM-ddTHH:mm:ss.fffZ', $null)
$pageCfg['lastModifiedTime'] = [Datetime]::ParseExact($page.lastModifiedTime, 'yyyy-MM-ddTHH:mm:ss.fffZ', $null)
$pageCfg['lastModifiedTimeEpoch'] = [int][double]::Parse((Get-Date ((Get-Date $pageCfg['lastModifiedTime']).ToUniversalTime()) -UFormat %s)) # Epoch
$pageCfg['pageLevel'] = $page.pageLevel -as [int]
$pageCfg['conversion'] = $config['conversion']['value']
$pageCfg['pagePrefix'] = & {
# 9 different scenarios
if ($pageCfg['pageLevel'] -eq 1) {
# 1 -> 1, 2 -> 1, or 3 -> 1
''
}else {
if ($previousPage) {
if ($previousPage['pageLevel'] -lt $pageCfg['pageLevel']) {
# 1 -> 2, 1 -> 3, or 2 -> 3
"$( $previousPage['filePathRel'] )$( [io.path]::DirectorySeparatorChar )"
}elseif ($previousPage['pageLevel'] -eq $pageCfg['pageLevel']) {
# 2 -> 2, or 3 -> 3
"$( Split-Path $previousPage['filePathRel'] -Parent )$( [io.path]::DirectorySeparatorChar )"
}else {
# 3 -> 2 (or 4 -> 2, but 4th level subpages don't exist, but technically this supports it)
$split = $previousPage['filePathRel'].Split([io.path]::DirectorySeparatorChar)
$index = $pageCfg['pageLevel'] - 1 - 1 # If page level n, the prefix should be n-1
if ($index -lt 0) {
$index = 0 # The shallowest subpage must be a child of a first level page, i.e. $split[0]
}
"$( $split[0..$index] -join [io.path]::DirectorySeparatorChar )$( [io.path]::DirectorySeparatorChar )"
}
}else {
'' # Should never end up here
}
}
}
# Win32 path limits. E.g. 'C:\path\to\file' or 'C:\path\to\folder'
# Absolute path:
# - Win32: Max 259 characters for files, Max 247 characters for directories.
# File or directory name:
# - Max 255 characters long for file or folder names
# Non-Win32 path limits. E.g. '\\?\C:\path\to\file' or '\\?\C:\path\to\folder'. Prefixing with '\\?\' allows Windows Powershell <= 5 (based on Win32) to support long absolute paths.
# Absolute path:
# - N.A.
# File or directory name:
# - Max 255 characters long for file or folder names
# See: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file?redirectedfrom=MSDN#maxpath
# Normalize the final .md file path. Page names can be very long, and can exceed the max absolute path length, or max file or folder name on a Windows system.
$pageCfg['filePathRel'] = & {
$filePathRel = "$( $pageCfg['pagePrefix'] )$( $pageCfg['nameCompat'] )"
# in case multiple pages with the same name exist in a section, postfix the filename
$recurrence = 0
foreach ($p in $sectionCfg['pages']) {
if ($p['pagePrefix'] -eq $pageCfg['pagePrefix'] -and $p['pathFromRoot'] -eq $pageCfg['pathFromRoot']) {
$recurrence++
}
}
if ($recurrence -gt 0) {
$filePathRel = "$filePathRel-$recurrence"
}
$filePathRel | Truncate-PathFileName -Length $config['mdFileNameAndFolderNameMaxLength']['value'] # Truncate to no more than 255 characters so we don't hit the folder name limit on most file systems on Windows / Linux
}
$pageCfg['filePathRelUnderscore'] = $pageCfg['filePathRel'].Replace( [io.path]::DirectorySeparatorChar, '_' )
$pageCfg['filePathNormal'] = & {
$pathWithoutExtension = if ($config['prefixFolders']['value'] -eq 2) {
[io.path]::combine( $cfg['notesDirectory'], $sectionCfg['nameCompat'], "$( $pageCfg['filePathRelUnderscore'] )" )
}else {
[io.path]::combine( $cfg['notesDirectory'], $sectionCfg['nameCompat'], "$( $pageCfg['filePathRel'] )" )
}
"$( $pathWithoutExtension | Truncate-PathFileName -Length ($config['mdFileNameAndFolderNameMaxLength']['value'] - 3) ).md" # Truncate to no more than 255 characters so we don't hit the file name limit on Windows / Linux
}
$pageCfg['filePathLong'] = "\\?\$( $pageCfg['filePathNormal'] )" # A non-Win32 path. Prefixing with '\\?\' allows Windows Powershell <= 5 (based on Win32) to support long absolute paths.
$pageCfg['filePath'] = if ($PSVersionTable.PSVersion.Major -le 5) {
$pageCfg['filePathLong'] # Add support for long paths on Powershell 5
}else {
$pageCfg['filePathNormal'] # Powershell Core supports long file paths
}
$pageCfg['fileDirectory'] = Split-Path $pageCfg['filePathNormal'] -Parent
$pageCfg['fileName'] = Split-Path $pageCfg['filePathNormal'] -Leaf
$pageCfg['fileExtension'] = if ($pageCfg['filePathNormal'] -match '(\.[^.]+)$') { $matches[1] } else { '' }
$pageCfg['fileBaseName'] = $pageCfg['fileName'] -replace "$( [regex]::Escape($pageCfg['fileExtension']) )$", ''
$pageCfg['pdfExportFilePathTmp'] = [io.path]::combine( (Split-Path $pageCfg['filePath'] -Parent ), "$( $pageCfg['id'] )-$( $pageCfg['lastModifiedTimeEpoch'] ).pdf" ) # Publishing a .pdf seems to be limited to 204 characters. So we will export the .pdf to a unique file name, then rename it to the actual name
$pageCfg['pdfExportFilePath'] = if ( ($pageCfg['fileName'].Length + ('.pdf'.Length - '.md'.Length)) -le $config['mdFileNameAndFolderNameMaxLength']['value']) {
$pageCfg['filePath'] -replace '\.md$', '.pdf'
}else {
$pageCfg['filePath'] -replace '.\.md$', '.pdf' # Trim 1 character in the basename when replacing the extension
}
$pageCfg['levelsPrefix'] = if ($config['medialocation']['value'] -eq 2) {
''
}else {
if ($config['prefixFolders']['value'] -eq 2) {
"$( '../' * ($pageCfg['levelsFromRoot'] + 1 - 1) )"
}else {
"$( '../' * ($pageCfg['levelsFromRoot'] + $pageCfg['pageLevel'] - 1) )"
}
}
$pageCfg['tmpPath'] = & {
$dateNs = Get-Date -Format "yyyy-MM-dd-HH-mm-ss-fffffff"
if ($env:OS -match 'windows') {
# Ensure $env:TEMP is not MSDOS 8.3 shortened name, but the actual full path. See: https://superuser.com/questions/1524767/powershell-uses-the-short-8-3-form-for-envtemp
[io.path]::combine((Get-Item $env:TEMP).FullName, $cfg['notebookName'], $dateNs)
}else {
[io.path]::combine('/tmp', $cfg['notebookName'], $dateNs)
}
}
$pageCfg['mediaParentPath'] = if ($config['medialocation']['value'] -eq 2) {
$pageCfg['fileDirectory']
}else {
$cfg['notesBaseDirectory']
}
$pageCfg['mediaPath'] = [io.path]::combine( $pageCfg['mediaParentPath'], 'media' )
$pageCfg['mediaParentPathPandoc'] = [io.path]::combine( $pageCfg['tmpPath'] ).Replace( [io.path]::DirectorySeparatorChar, '/' ) # Pandoc outputs paths in markdown with with front slahes after the supplied <mediaPath>, e.g. '<mediaPath>/media/image.png'. So let's use a front-slashed supplied mediaPath
$pageCfg['mediaPathPandoc'] = [io.path]::combine( $pageCfg['tmpPath'], 'media').Replace( [io.path]::DirectorySeparatorChar, '/' ) # Pandoc outputs paths in markdown with with front slahes after the supplied <mediaPath>, e.g. '<mediaPath>/media/image.png'. So let's use a front-slashed supplied mediaPath
$pageCfg['docxExportFilePath'] = if ($config['docxNamingConvention']['value'] -eq 1) {
[io.path]::combine( $cfg['notesDocxDirectory'], "$( $pageCfg['id'] )-$( $pageCfg['lastModifiedTimeEpoch'] ).docx" )
}else {
[io.path]::combine( $cfg['notesDocxDirectory'], "$( $pageCfg['pathFromRootCompat'] ).docx" )
}
$pageCfg['insertedAttachments'] = @(
& {
$pagexml = Get-OneNotePageContent -OneNoteConnection $OneNoteConnection -PageId $pageCfg['object'].ID
# Search recursively for all attachment(s). This includes attachments nested in tables etc.
$ns = new-object Xml.XmlNamespaceManager $pagexml.NameTable
$ns.AddNamespace("one", $pagexml.DocumentElement.NamespaceURI)
$insertedFiles = $pagexml.SelectNodes("//one:InsertedFile", $ns)
foreach ($i in $insertedFiles) {
$attachmentCfg = [ordered]@{}
$attachmentCfg['object'] = $i
$attachmentCfg['nameCompat'] = $i.preferredName | Remove-InvalidFileNameCharsInsertedFiles
$attachmentCfg['markdownFileName'] = $attachmentCfg['nameCompat'] | Encode-Markdown -Uri
$attachmentCfg['source'] = $i.pathCache
$attachmentCfg['destination'] = [io.path]::combine( $pageCfg['mediaPath'], $attachmentCfg['nameCompat'] )
$attachmentCfg
}
}
)
$pageCfg['mutations'] = @(
# Markdown mutations. Each search and replace is done against a string containing the entire markdown content
foreach ($attachmentCfg in $pageCfg['insertedAttachments']) {
@{
description = 'Change inserted attachment(s) filename references'
replacements = @(
@{
searchRegex = [regex]::Escape( $attachmentCfg['object'].preferredName )
replacement = "[$( $attachmentCfg['markdownFileName'] )]($( $pageCfg['mediaPathPandoc'] )/$( $attachmentCfg['markdownFileName'] ))"
}
)
}
}
@{
description = 'Replace media (e.g. images, attachments) absolute paths with relative paths'
replacements = @(
@{
# E.g. 'C:/temp/notes/mynotebook/media/somepage-image1-timestamp.jpg' -> '../media/somepage-image1-timestamp.jpg'
searchRegex = [regex]::Escape("$( $pageCfg['mediaParentPathPandoc'] )/") # Add a trailing front slash
replacement = $pageCfg['levelsPrefix']
}
)
}
@{
description = 'Add heading'
replacements = @(
@{
searchRegex = '^\s*'
replacement = & {
$heading = "# $( $pageCfg['object'].name )"
if ($config['headerTimestampEnabled']['value'] -eq 1) {
$heading += "`n`nCreated: $( $pageCfg['dateTime'].ToString('yyyy-MM-dd HH:mm:ss zz00') )"
$heading += "`n`nModified: $( $pageCfg['lastModifiedTime'].ToString('yyyy-MM-dd HH:mm:ss zz00') )"
$heading += "`n`n---`n`n"
}
$heading
}
}
)
}
if ($config['keepspaces']['value'] -eq 1 ) {
@{
description = 'Clear extra newlines between unordered (bullet) and ordered (numbered) list items, non-breaking spaces from blank lines, and `>` after unordered lists'
replacements = @(
# Remove non-breaking spaces
@{
searchRegex = [regex]::Escape([char]0x00A0)
replacement = ''
}
# Remove an extra newline between each occurrence of '- some unordered list item'
@{
searchRegex = '(\s*)- ([^\r\n]*)\r*\n\r*\n(?=\s*-)'
replacement = "`$1- `$2`n"
}
# Remove an extra newline between each occurrence of '1. some ordered list item'
@{
searchRegex = '(\s*)(\d+\.) ([^\r\n]*)\r*\n\r*\n(?=\s*\d+\.)'
replacement = "`$1`$2 `$3`n"
}
# Remove all '>' occurrences immediately following unordered lists
@{
searchRegex = '\n>[ ]*'
replacement = "`n"
}
)
}
}
if ($config['keepescape']['value'] -eq 1) {
@{
description = "Clear all '\' characters"
replacements = @(
@{
searchRegex = [regex]::Escape('\')
replacement = ''
}
)
}
}
elseif ($config['keepescape']['value'] -eq 2) {
@{
description = "Clear all '\' characters except those preceding alphanumeric characters"
replacements = @(
@{
searchRegex = '\\([^A-Za-z0-9])'
replacement = '$1'
}
)
}
}
& {
if ($config['newlineCharacter']['value'] -eq 1) {
@{
description = "Use LF for newlines"
replacements = @(
@{
searchRegex = '\r*\n'
replacement = "`n"
}
)
}
}else {
@{
description = "Use CRLF for newlines"
replacements = @(
@{
searchRegex = '\r*\n'
replacement = "`r`n"
}
)