forked from theohbrothers/ConvertOneNote2MarkDown
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathConvertOneNote2MarkDown-v2.ps1
1071 lines (919 loc) · 47.9 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
#Define global variables
[boolean]$global:activateDebug = 0
[boolean]$global:activateMOCForObsidian = 1
[boolean]$global:activateSubDir = 0
[boolean]$global:activateGlobalFileName = 0
[boolean]$global:activateGlobalTag = 1
[string]$global:globalTagPrefix = "#OneNote2Markdown4Obsidian"
[int]$global:fileCount = 0
[int]$global:pageNameRecurrenceCount = 1
[string]$global:filePrefix = "File-"
[string]$global:SpaceChar = " "
[int]$global:parsedLinksMatched = 0
[int]$global:parsedLinksNotMatched = 0
$global:parsedLinksAmbiguousMatched = 0
$global:PageNameHash = [System.Collections.Hashtable]::new()
$global:PageModifiedDateHash = [System.Collections.Hashtable]::new()
###################################################################################################################
# AUX FUNCTIONS
###################################################################################################################
Function Remove-InvalidFileNameChars {
param(
[Parameter(Mandatory = $true,
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[string]$Name
)
$newName = $Name.Split([IO.Path]::GetInvalidFileNameChars()) -join '-'
$newName = $newName.Replace('*', '-').Replace('"', '').Replace('\', '-').Replace('/', '-').Replace('<', '-').Replace('>', '-').Replace(':', '').Replace('|', '-').Replace('?', '') #Obsidian non valid file name chars
$newName = $newName.Trim()
if (($global:activateDebug -eq 1) -and ($newName -ne $Name))
{
Write-Host "$($name) `nRenamed to '[[$($newName)]]'" -ForegroundColor Blue
}
return (((($newName -replace "\s", "$($global:SpaceChar)") -replace "\[", "(") -replace "\]", ")").Substring(0,$(@{$true=130;$false=$newName.length}[$newName.length -gt 150])))
}
Function Remove-InvalidIdNameChars {
param(
[Parameter(Mandatory = $true,
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[string]$Name
)
$newName = $Name.Split([IO.Path]::GetInvalidFileNameChars()) -join '-'
return (((($newName -replace "\s", "$($global:SpaceChar)") -replace "\{", "--") -replace "\}", "--").Substring(0,$(@{$true=130;$false=$newName.length}[$newName.length -gt 150])))
}
Function Remove-InvalidFileNameCharsInsertedFiles {
param(
[Parameter(Mandatory = $true,
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[string]$Name,
[string]$Replacement = "",
[string]$SpecialChars = "#$%^*[]'<>!@{};"
)
$rePattern = ($SpecialChars.ToCharArray() |ForEach-Object { [regex]::Escape($_) }) -join "|"
$newName = $Name.Split([IO.Path]::GetInvalidFileNameChars()) -join '-'
return ($newName -replace $rePattern,"" -replace "\s","$($global:SpaceChar)")
}
Function getGlobalTag()
{
if($global:activateGlobalTag -eq 1)
{
return $global:globalTagPrefix + "/" + (Get-Date -Format "yyyyMMdd")
}
return ""
}
Function saveHyperlinkToObject($object, $name)
{
$link = ""
$OneNote.GetHyperLinkToObject($object.ID, "", [ref]$link)
if ($link -and $name)
{
$link = [regex]::Match($link, "(?<=page-id={)(.*?)(?=})").Groups[1].Value
if ($link -ne "" -and !$global:PageIdArray[$link])
{
$global:PageNameHash.Add($link, $name)
$global:PageModifiedDateHash.Add($link, $object.lastModifiedTime)
}
}
}
Function parseFileNameRepetition($filePath)
{
$path = $filePath[0]
$newName = $filePath[1]
# in case multiple sections with the same name exist in a section, postfix the filename. Run after pages
if ([System.IO.File]::Exists("$($path)\$($newName).md")) {
#continue
$newName = "$($newName)-$global:pageNameRecurrenceCount"
$global:pageNameRecurrenceCount++
}
return $newName;
}
Function ProcessSections ($group, $FilePath, $notebookName) {
[string]$sectionGroupValue
if ($global:activateMOCForObsidian -eq 1) #Header for section group moc file
{
[string]$sectionGroupValue = "# $($group.Name)`n`n- --`nRelated: [[$($notebookName)]] $(getGlobalTag)"
saveHyperlinkToObject $group ($group.Name | Remove-InvalidFileNameChars)
}
foreach ($section in $group.Section) {
"--------------"
"### " + $section.Name
$sectionFileName = "$($section.Name)" | Remove-InvalidFileNameChars
# in case multiple sections with the same name exist in a section, postfix the filename. Run after pages
$sectionFileName = parseFileNameRepetition($FilePath, $sectionFileName)
if($global:activateSubDir -eq 1)
{
New-Item -Path "$($FilePath)" -Name "$($sectionFileName)" -ItemType "directory" -ErrorAction SilentlyContinue
}
[int]$previouspagelevel = 1
[string]$previouspagenamelevel1 = ""
[string]$previouspagenamelevel2 = ""
[string]$pageprefix = ""
[string]$sectionValue = ""
if ($global:activateMOCForObsidian -eq 1) #Header for section moc file
{
[string]$sectionValue = "# $($section.Name)`n`n- -- `nRelated: [[$($group.Name | Remove-InvalidFileNameChars)]] $(getGlobalTag)"
}
foreach ($page in $section.Page) {
# set page variables
if ($global:activateSubDir -eq 1) #Global if no sub dirs
{
$global:pageNameRecurrenceCount = 1
}
$pagelevel = $page.pagelevel
$pagelevel = $pagelevel -as [int]
$pageid = ""
$pageid = $page.ID
$pagename = ""
$pagename = $page.name | Remove-InvalidFileNameChars
$fullexportdirpath = ""
if($global:activateSubDir -eq 1)
{
$fullexportdirpath = "$($FilePath)\$($sectionFileName)"
}
else {
$fullexportdirpath = "$($FilePath)"
}
$fullexportpath = ""
#$fullexportpath = "$($fullfilepathwithoutextension).docx"
$subpagelinks = ""
$subpagelinkcountlevel1 = 0
$subpagelinkcountlevel2 = 0
$fullfilepathwithoutextension = "$($fullexportdirpath)\$($pagename)"
if ($global:activateMOCForObsidian)
{
# in case multiple pages with the same name exist in a section, postfix the filename. Run after pages
if ([System.IO.File]::Exists("$($fullfilepathwithoutextension).md")) {
#continue
$pagename = "$($pagename)-$global:pageNameRecurrenceCount"
$fullfilepathwithoutextension = "$($fullexportdirpath)\$($pagename)"
$global:pageNameRecurrenceCount++
}
}
# process for subpage prefixes
if ($pagelevel -eq 1) {
$pageprefix = ""
$previouspagenamelevel1 = $pagename
$previouspagenamelevel2 = ""
$previouspagelevel = 1
$subpagelinkcountlevel1 = 0
$parent = $sectionFileName
"#### " + $page.name
if ($global:activateMOCForObsidian -eq 1)
{
$sectionValue = $sectionValue + "`n- [[$($pagename)]]"
}
}
elseif ($pagelevel -eq 2) {
$pageprefix = "$($previouspagenamelevel1)"
$previouspagenamelevel2 = $pagename
$previouspagelevel = 2
$subpagelinkcountlevel2 = 0
$parent = $previouspagenamelevel1
"##### " + $page.name
if ($global:activateMOCForObsidian -eq 1)
{
# Set links to subpages
$orig = Get-Content -path "$($fullexportdirpath)\$($previouspagenamelevel1).md" -encoding utf8
$subpagelinks = $subpagelinks + "- [[$($pagename)]]"
$init = 3+$subpagelinkcountlevel1
$ende = $init+1
Set-Content -Path "$($fullexportdirpath)\$($previouspagenamelevel1).md" -Value $orig[0..$init], $subpagelinks, $orig[$ende..$orig.Length] -encoding utf8
$subpagelinkcountlevel1++
}
}
elseif ($pagelevel -eq 3) {
if ($previouspagelevel -eq 2){
$pageprefix = "$($previouspagenamelevel1)$($prefixjoiner)$($previouspagenamelevel2)"
$parent = $previouspagenamelevel2
}
# level 3 under level 1, without a level 2
elseif ($previouspagelevel -eq 1) {
$pageprefix = "$($previouspagenamelevel1)$($prefixjoiner)"
$parent = $previouspagenamelevel1
}
#and if previous was 3, do nothing/keep previous label
$previouspagelevel = 3
"####### " + $page.name
if ($global:activateMOCForObsidian -eq 1)
{
# Set links to subpages
$orig = Get-Content -path "$($fullexportdirpath)\$($previouspagenamelevel2).md" -encoding utf8
$subpagelinks = $subpagelinks + "- [[$($pagename)]]"
$init = 3+$subpagelinkcountlevel2
$ende = $init+1
Set-Content -Path "$($fullexportdirpath)\$($previouspagenamelevel2).md" -Value $orig[0..$init], $subpagelinks, $orig[$ende..$orig.Length] -encoding utf8
$subpagelinkcountlevel2++
}
}
if ($global:activateMOCForObsidian -ne 1)
{
#if level 2 or 3 (i.e. has a non-blank pageprefix)
if ($pageprefix) {
#create filename prefixes and filepath if prefixes selected
if ($prefixFolders -eq 2) {
$pagename = "$($pageprefix)_$($pagename)"
$fullfilepathwithoutextension = "$($fullexportdirpath)\$($pagename)"
}
#all else/default, create subfolders and filepath if subfolders selected
elseif ($global:activateSubDir -eq 1) {
New-Item -Path "$($fullexportdirpath)\$($pageprefix)" -ItemType "directory" -ErrorAction SilentlyContinue | Out-Null
$fullexportdirpath = "$($fullexportdirpath)\$($pageprefix)"
$fullfilepathwithoutextension = "$($fullexportdirpath)\$($pagename)"
$levelsprefix = "../"*($levelsfromroot+$pagelevel-1)+".."
}
}
elseif ($global:activateSubDir -eq 1)
{
$levelsprefix = "../"*($levelsfromroot)+".."
}
}
saveHyperlinkToObject $page $pagename
# set media location (central media folder at notebook-level or adjacent to .md file) based on initial user prompt
if ($medialocation -eq 2) {
$mediaPath = $fullexportdirpath
$levelsprefix = ""
}
else {
$mediaPath = $NotebookFilePath
}
$fullexportpath = "$($NotebookFilePath)\docx\$($pagename).docx"
# use existing or create new docx files
if ($usedocx -eq 2) {
# Only create new docx if doesn't exist
if (![System.IO.File]::Exists($fullexportpath)) {
# publish OneNote page to Word
try {
$OneNote.Publish($pageid, $fullexportpath, "pfWord", "")
}
catch {
Write-Host "Error while publishing file '$($page.name)' to docx: $($Error[0].ToString())" -ForegroundColor Red
$totalerr += "Error while publishing file '$($page.name)' to docx: $($Error[0].ToString())`r`n"
}
}
}
else{
# remove any existing docx files
if ([System.IO.File]::Exists($fullexportpath)) {
try {
Remove-Item -path $fullexportpath -Force -ErrorAction SilentlyContinue
}
catch {
Write-Host "Error removing intermediary '$($page.name)' docx file: $($Error[0].ToString())" -ForegroundColor Red
$totalerr += "Error removing intermediary '$($page.name)' docx file: $($Error[0].ToString())`r`n"
}
}
# publish OneNote page to Word
try {
$OneNote.Publish($pageid, $fullexportpath, "pfWord", "")
}
catch {
Write-Host "Error while publishing file '$($page.name)' to docx: $($Error[0].ToString())" -ForegroundColor Red
$totalerr += "Error while publishing file '$($page.name)' to docx: $($Error[0].ToString())`r`n"
}
}
# https://gist.github.com/heardk/ded40b72056cee33abb18f3724e0a580
try {
pandoc.exe -f docx -t $converter-simple_tables-multiline_tables-grid_tables+pipe_tables -i $fullexportpath -o "$($fullfilepathwithoutextension).md" --wrap=none --markdown-headings=atx --extract-media="$($mediaPath)"
}
catch {
Write-Host "Error while converting file '$($page.name)' to md: $($Error[0].ToString())" -ForegroundColor Red
$totalerr += "Error while converting file '$($page.name)' to md: $($Error[0].ToString())`r`n"
}
# export inserted file objects, removing any escaped symbols from filename so that links to them actually work
[xml]$pagexml = ""
$OneNote.GetPageContent($pageid, [ref]$pagexml, 7)
$pageinsertedfiles = $pagexml.Page.Outline.OEChildren.OE | Where-Object { $_.InsertedFile }
foreach ($pageinsertedfile in $pageinsertedfiles) {
New-Item -Path "$($mediaPath)" -Name "media" -ItemType "directory" -ErrorAction SilentlyContinue | Out-Null
$destfilename = ""
try {
$destfilename = ""
if($global:activateGlobalFileName -eq 1) #Uses global file name to avoid naming problems
{
$global:fileCount++
$destfilename = "$($global:filePrefix)$($global:fileCount)$([System.IO.Path]::GetExtension($pageinsertedfile.InsertedFile.preferredName))"
}
else {
$destfilename = $pageinsertedfile.InsertedFile.preferredName | Remove-InvalidFileNameCharsInsertedFiles
}
Copy-Item -Path "$($pageinsertedfile.InsertedFile.pathCache)" -Destination "$($mediaPath)\media\$($destfilename)" -Force
}
catch {
Write-Host "Error while copying file object '$($pageinsertedfile.InsertedFile.preferredName)' for page '$($page.name)': $($Error[0].ToString())" -ForegroundColor Red
$totalerr += "Error while copying file object '$($pageinsertedfile.InsertedFile.preferredName)' for page '$($page.name)': $($Error[0].ToString())`r`n"
}
# Change MD file Object Name References
try {
$pageinsertedfile2 = $pageinsertedfile.InsertedFile.preferredName.Replace("$","\$").Replace("^","\^").Replace("'","\'")
((Get-Content -path "$($fullfilepathwithoutextension).md" -Raw -encoding utf8).Replace("$($pageinsertedfile2)", "[$($destfilename)]($($mediaPath)/media/$($destfilename))")) | Set-Content -Path "$($fullfilepathwithoutextension).md" -encoding utf8
}
catch {
Write-Host "Error while renaming file object name references to '$($pageinsertedfile.InsertedFile.preferredName)' for file '$($page.name)': $($Error[0].ToString())" -ForegroundColor Red
$totalerr += "Error while renaming file object name references to '$($pageinsertedfile.InsertedFile.preferredName)' for file '$($page.name)': $($Error[0].ToString())`r`n"
}
}
# add YAML
$orig = Get-Content -path "$($fullfilepathwithoutextension).md" -encoding utf8
$orig[0] = "# $($page.name)"
$insert1 = "$($page.dateTime)"
$insert1 =[Datetime]::ParseExact($insert1, 'yyyy-MM-ddTHH:mm:ss.fffZ', $null)
$insert1 = $insert1.ToString("[[yyyy-MM-dd]] HH:mm:ss")
$insert2 = "- --"
$insert3 = "Related: [[$($parent)]]"
if($global:activateGlobalTag -eq 1)
{
$insert3 = $insert3 + " " + (getGlobalTag)
}
if($global:activateMOCForObsidian -eq 1)
{
Set-Content -Path "$($fullfilepathwithoutextension).md" -Value $orig[0..0], $insert1, $insert2, $insert3, $insert2, $orig[6..$orig.Length] -encoding utf8
}
else {
Set-Content -Path "$($fullfilepathwithoutextension).md" -Value $orig[0..0], $insert1, $insert2, $orig[6..$orig.Length] -encoding utf8
}
#Convert > to - [ ] (Todos)
if ($convertTodos -ne 2 )
{
try {
((Get-Content -path "$($fullfilepathwithoutextension).md" -Raw -encoding utf8).Replace("`r`n>`r`n","`r`n").Replace("`r`n>","`r`n- [ ]")) | Set-Content -Path "$($fullfilepathwithoutextension).md" -encoding utf8
}
catch {
Write-Host "Error while clearing double spaces from file '$($fullfilepathwithoutextension)' : $($Error[0].ToString())" -ForegroundColor Red
$totalerr += "Error while clearing double spaces from file '$($fullfilepathwithoutextension)' : $($Error[0].ToString())`r`n"
}
}
#Clear double spaces from bullets and nonbreaking spaces from blank lines
if ($keepspaces -ne 2 )
{
try {
((Get-Content -path "$($fullfilepathwithoutextension).md" -Raw -encoding utf8).Replace("`r`n`r`n|","`n`n|").Replace("`r`n`r`n","`r`n")) | Set-Content -Path "$($fullfilepathwithoutextension).md" -encoding utf8
}
catch {
Write-Host "Error while clearing double spaces from file '$($fullfilepathwithoutextension)' : $($Error[0].ToString())" -ForegroundColor Red
$totalerr += "Error while clearing double spaces from file '$($fullfilepathwithoutextension)' : $($Error[0].ToString())`r`n"
}
}
# rename images to have unique names - NoteName-Image#-HHmmssff.xyz
$timeStamp = (Get-Date -Format HHmmssff).ToString()
$timeStamp = $timeStamp.replace(':', '')
$images = Get-ChildItem -Path "$($mediaPath)/media" -Include "*.png", "*.gif", "*.jpg", "*.jpeg" -Recurse -ErrorAction SilentlyContinue | Where-Object { $_.Name.SubString(0,5) -match "image" }
foreach ($image in $images) {
$newimageName = ""
if($global:activateGlobalFileName -eq 1) #Uses global file name to avoid naming problems
{
$global:fileCount++
$newimageName = "$($global:filePrefix)$($global:fileCount)$($image.Extension)"
}
else {
$newimageName = "$($pagename.SubString(0,[math]::min(30,$pagename.length)))-$($image.BaseName)-$($timeStamp)$($image.Extension)"
}
# Rename Image
try {
Rename-Item -Path "$($image.FullName)" -NewName $newimageName -ErrorAction SilentlyContinue
}
catch {
Write-Host "Error while renaming image '$($image.FullName)' for page '$($page.name)': $($Error[0].ToString())" -ForegroundColor Red
$totalerr += "Error while renaming image '$($image.FullName)' for page '$($page.name)': $($Error[0].ToString())`r`n"
}
# Change MD file Image filename References
try {
((Get-Content -path "$($fullfilepathwithoutextension).md" -Raw -encoding utf8).Replace("$($image.Name)", "$($newimageName)")) | Set-Content -Path "$($fullfilepathwithoutextension).md" -encoding utf8
}
catch {
Write-Host "Error while renaming image file name references to '$($image.Name)' for file '$($page.name)': $($Error[0].ToString())" -ForegroundColor Red
$totalerr += "Error while renaming image file name references to '$($image.Name)' for file '$($page.name)': $($Error[0].ToString())`r`n"
}
}
# change MD file Image Path References
try {
# Change MD file Image Path References in Markdown
((Get-Content -path "$($fullfilepathwithoutextension).md" -Raw -encoding utf8).Replace("$($mediaPath.Replace("\","\\"))", "$($levelsprefix)")) | Set-Content -Path "$($fullfilepathwithoutextension).md" -encoding utf8
# Change MD file Image Path References in HTML
((Get-Content -path "$($fullfilepathwithoutextension).md" -Raw -encoding utf8).Replace("$($mediaPath)", "$($levelsprefix)")) | Set-Content -Path "$($fullfilepathwithoutextension).md" -encoding utf8
}
catch {
Write-Host "Error while renaming image file path references for file '$($page.name)': $($Error[0].ToString())" -ForegroundColor Red
$totalerr += "Error while renaming image file path references for file '$($page.name)': $($Error[0].ToString())`r`n"
}
# Clear backslash escape symbols
if ($keepescape -eq 2 ) {
#do nothing
}
elseif ($keepescape -eq 3) {
((Get-Content -path "$($fullfilepathwithoutextension).md" -Raw -encoding utf8).Replace("\",'/')) | Set-Content -Path "$($fullfilepathwithoutextension).md" -encoding utf8
}
else {
((Get-Content -path "$($fullfilepathwithoutextension).md" -Raw -encoding utf8).Replace("\",'')) | Set-Content -Path "$($fullfilepathwithoutextension).md" -encoding utf8
}
# Cleanup Word files
try {
if ($keepdocx -ne 2) {
Remove-Item -path "$fullexportpath" -Force -ErrorAction SilentlyContinue
}
}
catch {
Write-Host "Error removing intermediary '$($page.name)' docx file: $($Error[0].ToString())" -ForegroundColor Red
$totalerr += "Error removing intermediary '$($page.name)' docx file: $($Error[0].ToString())`r`n"
}
}
if($global:activateMOCForObsidian -eq 1)
{
$sectionValue = $sectionValue + "`n- --"
New-Item -Path "$($FilePath)" -Name "$($sectionFileName).md" -ItemType "file" -Value "$($sectionValue)" -ErrorAction SilentlyContinue
$sectionGroupValue = $sectionGroupValue + "`n- [[$($sectionFileName)]]"
saveHyperlinkToObject $section $sectionFileName
}
}
if($global:activateMOCForObsidian -eq 1)
{
$sectionGroupValue = $sectionGroupValue + "`n- --"
return $sectionGroupValue
}
}
Function FindNameById($objId)
{
return $global:PageNameHash[$objId]
}
Function MatchLinkToFile ($notesdestpath, $link)
{
$files = Get-ChildItem -Path $notesdestpath -Recurse -Include "$($link).md"
if (!$files)
{
$files = Get-ChildItem -Path $notesdestpath -Recurse -Include "*$($link)*.md"
}
if (!$files)
{
#Search without special chars
$searchTerm = $link -Replace "[^A-Za-z0-9]", '*'
$files = Get-ChildItem -Path $notesdestpath -Recurse -Include "*$($searchTerm)*.md"
}
if($files.Length -gt 0)
{
foreach ($file in $files) {
$link = $file.Name -replace ".md", ''
break
}
if(($files -is [array]) -and ($files.Length -gt 1))
{
$link = $link + "???"
}
}
else {
$link = ""
}
return $link
}
Function parseLinkForPattern($file, $linkExp, $nameExp)
{
# Find links based on regex
$secLinks = (Get-Content -path $file.FullName -Raw -encoding utf8) | Select-String -Pattern "$($linkExp)" -AllMatches | %{$_.matches} | %{$_.Value}
foreach($link in $secLinks)
{
#$url = [regex]::Match($link,"(?=onenote:)(.*?)(?=\))").Groups[1].Value
$LinkPageId = [regex]::Match($link,"(?<=page-id={)(.*?)(?=})").Groups[1].Value
#$LinkSectionId = [regex]::Match($link,"(?<=section-id={)(.*?)(?=})").Groups[1].Value
#$linkObjectId = [regex]::Match($link,"(?<=object-id={)(.*?)(?=})").Groups[1].Value
#$LinkBasePath = [regex]::Match($link,"(?<=base-path=)(.*?)(?=\))").Groups[1].Value
$linkName = ""
#Find usig object ids
if ($LinkPageId)
{
$linkName = FindNameById $LinkPageId
}
if($linkName)
{
$linkName = $linkName | Remove-InvalidFileNameChars
}
#Find using file search
if(!$linkName -and $linkExp -and $nameExp)
{
$linkName = [regex]::Match($link,$nameExp).Groups[1].Value | Remove-InvalidFileNameChars
$linkName = $linkName.Replace("%20", " ")
$linkName = MatchLinkToFile $notesdestpath $linkName
}
if ($linkName)
{
$append = ""
$global:parsedLinksMatched++
if ($linkName.Contains("???"))
{
$linkName = $linkName.Replace("???", '')
$append = "#LinkAmbiguous"
$global:parsedLinksAmbiguousMatched++
}
else {
$global:parsedLinksMatched++
}
((Get-Content -path $file.FullName -Raw -encoding utf8).Replace("$($link)", "[[$($linkName)]] $($append)")) | Set-Content -Path $file.FullName -encoding utf8
}
elseif($nameExp){
((Get-Content -path $file.FullName -Raw -encoding utf8).Replace("$($link)", "$($link) #LinkNotResolved")) | Set-Content -Path $file.FullName -Encoding UTF8
$global:parsedLinksNotMatched++
}
}
}
Function ParseLinks($notesdestpath)
{
$files = Get-ChildItem -Path $notesdestpath -Recurse -Include "*.md"
foreach ($file in $files) {
try {
# All onenote Links
$linkExp = "(?=\[.*\]\(onenote:)(.*?)(?<=\.one\))"
$nameExp = ""
parseLinkForPattern $file $linkExp $nameExp
# Section Links
$linkExp = "(?=\[.*\(onenote:#section)(.*?)(?<=\.one\))"
$nameExp = "(?<=\[)(.*?)(?=\])"
parseLinkForPattern $file $linkExp $nameExp
# Page and Paragraph links to page
$linkExp = "(?=\[.*\(onenote:.*§ion)(.*?)(?<=\.one\))"
$nameExp = "(?<=\]\(onenote:#)(.*?)(?=§ion-id)"
parseLinkForPattern $file $linkExp $nameExp
# Unsesolved onenote links -> [[NAME]]
$linkExp = "(?=\[)(.*?)(\]\(onenote:)(.*?)(?<=\))"
$nameExp = "(?<=\[)(.*?)(?=\])"
parseLinkForPattern $file $linkExp $nameExp
}
catch
{
Write-Host "Error resolving links for '$($file.name)': $($Error[0].ToString())" -ForegroundColor Red
$totalerr += "Error resolving links for '$($file.name)': $($Error[0].ToString())`r`n"
}
}
Write-Host "Total links found`t:`t$($global:parsedLinksMatched + $global:parsedLinksNotMatched + $global:parsedLinksAmbiguousMatched)"
Write-Host "`tMatched`t`t:`t$($global:parsedLinksMatched)"
Write-Host "`tAmbiguous`t:`t$($global:parsedLinksAmbiguousMatched)"
Write-Host "`tNot matched`t:`t$($global:parsedLinksNotMatched)"
}
###################################################################################################################
# INPUTS
###################################################################################################################
""
"-----------------------------------------------"
# ask for the Notes root path
"Enter the (preferably empty!) folder path (without trailing backslash!) that will contain your resulting Notes structure. ex. 'c:\temp\notes'"
$notesdestpath = Read-Host -Prompt "Entry"
""
"-----------------------------------------------"
#prompt to use existing word docs (90% faster)
""
"-----------------------------------------------"
"1: Create new .docx files - Default"
"2: Use existing .docx files (90% faster)"
[int] $usedocx = Read-Host -Prompt "Entry"
#prompt to discard intermediate word docs
""
"-----------------------------------------------"
"1: Discard intermediate .docx files - Default"
"2: Keep .docx files"
[int] $keepdocx = Read-Host -Prompt "Entry"
""
"-----------------------------------------------"
# prompt MOC for Obsidian
"1: Use Map of Contents Structure - Default"
"`t--For linking in Obsidian--"
"`t`t- All files in the same folder"
"`t`t- Pages for sections and section groups containing links to child pages/sections"
"`t`t- Pages link to subpages (3 levels)"
"2: Select other structure"
[Int]$prefixFolders = 1
[int]$medialocation = 1
$optMOCForObsidian = Read-Host -Prompt "Entry"
if ($optMOCForObsidian -ne 2)
{
$global:activateMOCForObsidian = 1
$global:activateSubDir = 0
$global:activateGlobalFileName = 1
$prefixFolders = 2
}
else {
$global:activateSubDir = 1
$global:activateGlobalFileName = 0
$global:activateMOCForObsidian = 0
}
if (!$global:activateMOCForObsidian)
{
""
"-----------------------------------------------"
# prompt for prefix vs subfolders
"1: Create folders for subpages (e.g. Page\Subpage.md)- Default"
"2: Add prefixes for subpages (e.g. Page_Subpage.md)"
$prefixFolders = Read-Host -Prompt "Entry"
if ($prefixFolders -eq 2) {
$prefixFolders = 2
$prefixjoiner = "_"
}
else {
$prefixFolders = 1
$prefixjoiner = "\"
$global:activateSubDir = 1
}
}
if (!$global:activateMOCForObsidian)
{
#prompt for 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"
$medialocation = Read-Host -Prompt "Entry"
}
#prompt for generic file naming
""
"-----------------------------------------------"
"1: Use generic file names to avoid name errors (File-<Number>) - Default"
"2: Maintain original file names"
if((Read-Host -Prompt "Entry") -eq 2)
{
$global:activateGlobalFileName = 0
}
#prompt for conversion type
""
"Select conversion type"
"-----------------------------------------------"
"1: markdown (Pandoc) - Default"
"2: commonmark (CommonMark Markdown)"
"3: gfm (GitHub-Flavored Markdown)"
"4: markdown_mmd (MultiMarkdown)"
"5: markdown_phpextra (PHP Markdown Extra)"
"6: markdown_strict (original unextended Markdown)"
[int]$conversion = Read-Host -Prompt "Entry: "
if ($conversion -eq 2){ $converter = "commonmark"}
elseif ($conversion -eq 3){ $converter = "gfm"}
elseif ($conversion -eq 4){ $converter = "markdown_mmd"}
elseif ($conversion -eq 5){ $converter = "markdown_phpextra"}
elseif ($conversion -eq 6){ $converter = "markdown_strict"}
else { $converter = "markdown"}
#prompt to clear double spaces between bullets
"-----------------------------------------------"
"1: Clear double spaces in bullets - Default"
"2: Keep double spaces"
[int] $keepspaces = Read-Host -Prompt "Entry"
#Convert ">" (Todos) to "- [ ]"
"-----------------------------------------------"
"1: Convert '>' to '- [ ]' - Default"
"2: Keep '>'"
[int] $convertTodos = Read-Host -Prompt "Entry"
# prompt to clear escape symbols from md files
[int] $keepescape = 3 # (\ -> /)
if (!$global:activateMOCForObsidian)
{
"-----------------------------------------------"
"1: Clear '\' symbol escape character from files"
"2: Keep '\' symbol escape"
$keepescape = Read-Host -Prompt "Entry"
}
# prompt to resolve links for obsidian
"-----------------------------------------------"
"1: Convert OneNote links to Markdown [[Link]]"
"2: Keep onenote links"
[int] $resolveLinks = Read-Host -Prompt "Entry"
if ($global:activateMOCForObsidian)
{
# prompt to activate a global tag
"-----------------------------------------------"
"1: Add a global tag to all notes - Default ($($global:globalTagPrefix)/yyyymmdd))"
"2: Don't add a global tag"
[int] $optActivateGlobalTag = Read-Host -Prompt "Entry"
if ($optActivateGlobalTag -ne 2)
{
$global:activateGlobalTag = 1
# prompt to personalize global tag
"-----------------------------------------------"
"1: Use Default: $($global:globalTagPrefix)/yyyymmdd))"
"2: Personalize"
[int] $optPersonalizeTag = Read-Host -Prompt "Entry"
if ($optPersonalizeTag -eq 2)
{
do {
# prompt new tag
"-----------------------------------------------"
"1: Use Default: $($global:globalTagPrefix)/yyyymmdd))"
"2: Type new tag"
$global:globalTagPrefix = Read-Host -Prompt "Entry"
"Your new tag is: '$($global:globalTagPrefix)'"
"Press 2 to change or any key to confirm."
$optPersonalizeTag = Read-Host -Prompt "Entry"
} while ($optPersonalizeTag -eq 2)
}
}
else
{
$global:activateGlobalTag = 0
}
}
###################################################################################################################
# Start
###################################################################################################################
if (Test-Path -Path $notesdestpath) {
# open OneNote hierarchy
$OneNote = New-Object -ComObject OneNote.Application
[xml]$Hierarchy = ""
$totalerr = ""
$OneNote.GetHierarchy("", [Microsoft.Office.InterOp.OneNote.HierarchyScope]::hsPages, [ref]$Hierarchy)
foreach ($notebook in $Hierarchy.Notebooks.Notebook) {
" "
$notebook.Name
$notebookFileName = "$($notebook.Name)" | Remove-InvalidFileNameChars
if ($global:activateSubDir -eq 1)
{
New-Item -Path "$($notesdestpath)\" -Name "$($notebookFileName)" -ItemType "directory" -ErrorAction SilentlyContinue
$NotebookFilePath = "$($notesdestpath)\$($notebookFileName)"
}
else {
$NotebookFilePath = "$($notesdestpath)"
}
$levelsfromroot = 0
New-Item -Path "$($NotebookFilePath)" -Name "docx" -ItemType "directory" -ErrorAction SilentlyContinue
$notebookContent = ""
if($global:activateGlobalTag -eq 1)
{
$notebookContent = $notebookContent + (getGlobalTag) + "`n`n"
}
"=============="
#process any sections that are not in a section group
if ($global:activateMOCForObsidian -eq 1)
{
$notebookContent = $notebookContent + (ProcessSections $notebook $NotebookFilePath $notebookFileName)[-1]
}
else {
ProcessSections $notebook $NotebookFilePath
}
#start looping through any top-level section groups in the notebook
foreach ($sectiongroup1 in $notebook.SectionGroup) {
$levelsfromroot = 1
if ($sectiongroup1.isRecycleBin -ne 'true') {
"# " + $sectiongroup1.Name
$sectiongroupFileName1 = "$($sectiongroup1.Name)" | Remove-InvalidFileNameChars
$sectiongroupFilePath1 = ""
if ($global:activateSubDir -eq 1)
{
New-Item -Path "$($notesdestpath)\$($notebookFileName)" -Name "$($sectiongroupFileName1)" -ItemType "directory" -ErrorAction SilentlyContinue
$sectiongroupFilePath1 = "$($notesdestpath)\$($notebookFileName)\$($sectiongroupFileName1)"
}
else {
$sectiongroupFilePath1 = $NotebookFilePath
}
$sectiongroupFileName1 = parseFileNameRepetition($sectiongroupFilePath1, $sectiongroupFileName1)
[string]$sectionGroup1Value = ""
if ($global:activateMOCForObsidian -eq 1)
{
$sectionGroup1Value = (ProcessSections $sectiongroup1 $sectiongroupFilePath1)[-1]
}
else {
ProcessSections $sectiongroup1 $sectiongroupFilePath1
}
#start looping through any 2nd level section groups within the 1st level section group
foreach ($sectiongroup2 in $sectiongroup1.SectionGroup) {
$levelsfromroot = 2
if ($sectiongroup2.isRecycleBin -ne 'true') {
"## " + $sectiongroup2.Name
$sectiongroupFileName2 = "$($sectiongroup2.Name)" | Remove-InvalidFileNameChars
$sectiongroupFilePath2 = ""
if ($global:activateSubDir -eq 1)
{
New-Item -Path "$($notesdestpath)\$($notebookFileName)\$($sectiongroupFileName1)" -Name "$($sectiongroupFileName2)" -ItemType "directory" -ErrorAction SilentlyContinue
$sectiongroupFilePath2 = "$($notesdestpath)\$($notebookFileName)\$($sectiongroupFileName1)\$($sectiongroupFileName2)"
}
else {
$sectiongroupFilePath2 = $NotebookFilePath
}
$sectiongroupFileName2 = parseFileNameRepetition($sectiongroupFilePath2, $sectiongroupFileName2)
[string]$sectionGroup2Value = ""
if ($global:activateMOCForObsidian -eq 1)
{
$sectionGroup1Value = $sectionGroup1Value + "`n- [[$($sectiongroupFileName2)]]"
$sectionGroup2Value = (ProcessSections $sectiongroup2 $sectiongroupFilePath2)[-1]
}
else {
ProcessSections $sectiongroup2 $sectiongroupFilePath2
}
#start looping through any 2nd level section groups within the 1st level section group
foreach ($sectiongroup3 in $sectiongroup2.SectionGroup) {
$levelsfromroot = 3
if ($sectiongroup3.isRecycleBin -ne 'true') {
"### " + $sectiongroup3.Name
$sectiongroupFileName3 = "$($sectiongroup3.Name)" | Remove-InvalidFileNameChars
$sectiongroupFilePath3 = ""
if ($global:activateSubDir -eq 1)
{
New-Item -Path "$($notesdestpath)\$($notebookFileName)\$($sectiongroupFileName1)\$($sectiongroupFileName2)" -Name "$($sectiongroupFileName3)" -ItemType "directory" -ErrorAction SilentlyContinue
$sectiongroupFilePath3 = "$($notesdestpath)\$($notebookFileName)\$($sectiongroupFileName1)\$($sectiongroupFileName2)\$($sectiongroupFileName3)"
}
else {
$sectiongroupFilePath3 = $NotebookFilePath
}
$sectiongroupFileName3 = parseFileNameRepetition($sectiongroupFilePath3, $sectiongroupFileName3)
[string]$sectionGroup3Value = ""
if ($global:activateMOCForObsidian -eq 1)
{
$sectionGroup2Value = $sectionGroup2Value + "`n- [[$($sectiongroupFileName3)]]"
$sectionGroup3Value = (ProcessSections $sectiongroup3 $sectiongroupFilePath3)[-1]
}
ProcessSections $sectiongroup3 $sectiongroupFilePath3
#start looping through any 2nd level section groups within the 1st level section group
foreach ($sectiongroup4 in $sectiongroup3.SectionGroup) {
$levelsfromroot = 4
if ($sectiongroup4.isRecycleBin -ne 'true') {
"#### " + $sectiongroup4.Name
$sectiongroupFileName4 = "$($sectiongroup4.Name)" | Remove-InvalidFileNameChars
$sectiongroupFilePath4 = ""
if ($global:activateSubDir -eq 1)
{
New-Item -Path "$($notesdestpath)\$($notebookFileName)\$($sectiongroupFileName1)\$($sectiongroupFileName2)\$($sectiongroupFileName3)" -Name "$($sectiongroupFileName4)" -ItemType "directory" -ErrorAction SilentlyContinue
$sectiongroupFilePath4 = "$($notesdestpath)\$($notebookFileName)\$($sectiongroupFileName1)\$($sectiongroupFileName2)\$($sectiongroupFileName3)\$($sectiongroupFileName4)"
}
else {
$sectiongroupFilePath4 = $NotebookFilePath
}
$sectiongroupFileName4 = parseFileNameRepetition($sectiongroupFilePath4, $sectiongroupFileName4)
[string]$sectionGroup4Value = ""
if ($global:activateMOCForObsidian -eq 1)
{
$sectionGroup3Value = $sectionGroup3Value + "`n- [[$($sectiongroupFileName4)]]"
$sectionGroup4Value = (ProcessSections $sectiongroup4 $sectiongroupFilePath4)[-1]
}
else {
ProcessSections $sectiongroup4 $sectiongroupFilePath4
}
#start looping through any 2nd level section groups within the 1st level section group
foreach ($sectiongroup5 in $sectiongroup4.SectionGroup) {
$levelsfromroot = 5
if ($sectiongroup5.isRecycleBin -ne 'true') {
"#### " + $sectiongroup5.Name
$sectiongroupFileName5 = "$($sectiongroup5.Name)" | Remove-InvalidFileNameChars
$sectiongroupFilePath5 = ""
if ($global:activateSubDir -eq 1)
{
New-Item -Path "$($notesdestpath)\$($notebookFileName)\$($sectiongroupFileName1)\$($sectiongroupFileName2)\$($sectiongroupFileName3)\$($sectiongroupFileName4)" -Name "$($sectiongroupFileName5)" -ItemType "directory" -ErrorAction SilentlyContinue
$sectiongroupFilePath5 = "$($notesdestpath)\$($notebookFileName)\$($sectiongroupFileName1)\$($sectiongroupFileName2)\$($sectiongroupFileName3)\$($sectiongroupFileName4)\\$($sectiongroupFileName5)"
}
else {