-
Notifications
You must be signed in to change notification settings - Fork 116
/
ConvertOneNote2MarkDown.ps1
254 lines (229 loc) · 12.3 KB
/
ConvertOneNote2MarkDown.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
<#
.SYNOPSIS
Convert OneNote to Markdown Tool
Copyright (C) 2021 Sjoerd de Valk
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
.DESCRIPTION
This script will convert your OneNote notebook, sections and pages to Markdown files using the OneNote InterOp API.
Reference: https://matthewsetter.com/technical-documentation/asciidoc/convert-markdown-to-asciidoc-with-kramdoc/
Github: https://github.com/asciidoctor/kramdown-asciidoc
.EXAMPLE
Run this script file as follows: .\ConvertOneNote2MarkDown.ps1
#>
Function Remove-InvalidFileNameChars {
param(
[Parameter(Mandatory = $true,
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[String]$Name
)
$newName = $Name.Split([IO.Path]::GetInvalidFileNameChars()) -join '_'
return ($newName.Replace(" ", "_"))
}
# ask for the Notes root path
$notesdestpath = Read-Host -Prompt "Enter the (preferably empty!) folder path (without trailing backslash!) that will contain your resulting Notes structure. ex. 'c:\temp\notes'"
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) {
#if ($notebook.Name -eq "Company X Notebook" ) {
" "
$notebook.Name
$notebookFileName = "$($notebook.Name)" | Remove-InvalidFileNameChars
New-Item -Path "$($notesdestpath)\" -Name "$($notebookFileName)" -ItemType "directory" -ErrorAction SilentlyContinue
"=============="
foreach ($sectiongroup in $notebook.SectionGroup) {
if ($sectiongroup.isRecycleBin -ne 'true') {
"## " + $sectiongroup.Name
}
}
foreach ($section in $notebook.Section) {
#if ($section.Name -eq "Adjust Forms and Workflow Section") {
"--------------"
"### " + $section.Name
$sectionFileName = "$($section.Name)" | Remove-InvalidFileNameChars
New-Item -Path "$($notesdestpath)\$($notebookFileName)" -Name "$($sectionFileName)" -ItemType "directory" -ErrorAction SilentlyContinue
[int]$previouspagelevel = 1
[string]$previouspagenamelevel1 = ""
[string]$previouspagenamelevel2 = ""
[string]$pageprefix = ""
$pageRecurrence = 1
foreach ($page in $section.Page) {
"#### " + $page.name
#if ($page.name -eq "Workflow Documentation Page") {
# set page variables
$pagelevel = $page.pagelevel
$pagelevel = $pagelevel -as [int]
$pageid = ""
$pageid = $page.ID
$pagename = ""
$pagename = $page.name | Remove-InvalidFileNameChars
$fullexportdirpath = ""
$fullexportdirpath = "$($notesdestpath)\$($notebookFileName)\$($sectionFileName)"
$fullexportpathwithoutextension = ""
$fullexportpath = ""
# determine right name prefix based on pagelevel
if ($pagelevel -eq 1) {
$pageprefix = ""
$previouspagenamelevel1 = $pagename
$previouspagenamelevel2 = ""
$previouspagelevel = 1
}
elseif ($pagelevel -gt $previouspagelevel) {
if ($pagelevel -eq 2) {
$pageprefix = "$($previouspagenamelevel1)"
$previouspagenamelevel2 = $pagename
$previouspagelevel = 2
}
if ($pagelevel -eq 3) {
$pageprefix = "$($previouspagenamelevel1)_$($previouspagenamelevel2)"
$previouspagelevel = 3
}
}
elseif ($pagelevel -eq $previouspagelevel -and $pagelevel -ne 1) {
if ($pagelevel -eq 2) {
$pageprefix = "$($previouspagenamelevel1)"
$previouspagenamelevel2 = $pagename
}
if ($pagelevel -eq 3) {
$pageprefix = "$($previouspagenamelevel1)_$($previouspagenamelevel2)"
}
}
elseif ($pagelevel -lt $previouspagelevel -and $pagelevel -ne 1) {
if ($pagelevel -eq 2) {
$pageprefix = "$($previouspagenamelevel1)"
$previouspagenamelevel2 = $pagename
$previouspagelevel = 2
}
}
if ($pageprefix) {
$pagename = "$($pageprefix)_$($pagename)"
}
$fullexportpathwithoutextension = "$($fullexportdirpath)\$($pagename)"
$fullexportpath = "$($fullexportpathwithoutextension).docx"
# in case multiple pages with the same name exist in a section, postfix the filename
if ([System.IO.File]::Exists("$($fullexportpathwithoutextension).md")) {
$pagename = "$($pagename)_$pageRecurrence"
$pageRecurrence++
}
$fullexportpathwithoutextension = "$($fullexportdirpath)\$($pagename)"
$fullexportpath = "$($fullexportpathwithoutextension).docx"
# make sure there is no existing Word file
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"
}
# convert Word to Markdown
# https://gist.github.com/heardk/ded40b72056cee33abb18f3724e0a580
try {
pandoc.exe -f docx -t gfm -i $fullexportpath -o "$($fullexportpathwithoutextension).md" --wrap=none --markdown-headings=atx --extract-media="$($fullexportdirpath)"
}
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
[xml]$pagexml = ""
$OneNote.GetPageContent($pageid, [ref]$pagexml, 7)
$pageinsertedfiles = $pagexml.Page.Outline.OEChildren.OE | Where-Object { $_.InsertedFile }
foreach ($pageinsertedfile in $pageinsertedfiles) {
$destfilename = ""
try {
$destfilename = $pageinsertedfile.InsertedFile.preferredName | Remove-InvalidFileNameChars
Copy-Item -Path "$($pageinsertedfile.InsertedFile.pathCache)" -Destination "$($fullexportdirpath)\$($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 {
((Get-Content -LiteralPath "$($fullexportpathwithoutextension).md" -Raw).Replace("$($pageinsertedfile.InsertedFile.preferredName)", "[$($destfilename)](./$($destfilename))")) | Set-Content -LiteralPath "$($fullexportpathwithoutextension).md"
}
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"
}
}
# rename images
$timeStamp = (Get-Date -Format o).ToString()
$timeStamp = $timeStamp.replace(':', '')
$re = [regex]"\d{4}-\d{2}-\d{2}T"
$images = Get-ChildItem -Path "$($fullexportdirpath)/media" -Include "*.png", "*.gif", "*.jpg", "*.jpeg" -Recurse -ErrorAction SilentlyContinue | Where-Object { $_.Name -notmatch $re }
foreach ($image in $images) {
$newimageName = "$($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 Name References
try {
((Get-Content -LiteralPath "$($fullexportpathwithoutextension).md" -Raw).Replace("$($image.Name)", "$($newimageName)")) | Set-Content -LiteralPath "$($fullexportpathwithoutextension).md"
}
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 -LiteralPath "$($fullexportpathwithoutextension).md" -Raw).Replace("$($fullexportdirpath.Replace("\","\\"))/", "")) | Set-Content -LiteralPath "$($fullexportpathwithoutextension).md"
# Change MD file Image Path References in HTML
((Get-Content -LiteralPath "$($fullexportpathwithoutextension).md" -Raw).Replace("$($fullexportdirpath)/", "")) | Set-Content -LiteralPath "$($fullexportpathwithoutextension).md"
}
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"
}
# Cleanup Word files
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"
}
#}
}
#}
}
#}
}
# release OneNote hierarchy
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($OneNote)
Remove-Variable OneNote
$totalerr
}
else {
Write-Host "This path is NOT valid"
}