| 1 | param([Parameter(Mandatory=$true)][string]$Root, [Parameter(Mandatory=$true)][string]$CloneHost) |
| 2 | Set-StrictMode -Version Latest |
| 3 | $ErrorActionPreference = 'Stop' |
| 4 | & "$PSScriptRoot\cold-current.ps1" -Root $Root -CloneHost $CloneHost |
| 5 | $namespace = 'http://schemas.microsoft.com/office/onenote/2010/onenote' |
| 6 | $app = New-Object -ComObject OneNote.Application |
| 7 | $notebookId = '' |
| 8 | function Read-Tree { |
| 9 | $deadline = [DateTime]::UtcNow.AddSeconds(60) |
| 10 | do { |
| 11 | $hierarchy = '' |
| 12 | $app.GetHierarchy($notebookId, 4, [ref]$hierarchy, 1) |
| 13 | [xml]$tree = $hierarchy |
| 14 | if (@($tree.SelectNodes('//*[local-name()="Section"]')).Count -ge 4) { return $hierarchy } |
| 15 | Start-Sleep -Milliseconds 500 |
| 16 | } while ([DateTime]::UtcNow -lt $deadline) |
| 17 | throw 'The notebook did not finish loading.' |
| 18 | } |
| 19 | try { |
| 20 | $app.OpenHierarchy((Join-Path $Root 'notebook'), '', [ref]$notebookId, 0) |
| 21 | $hierarchy = Read-Tree |
| 22 | [IO.File]::WriteAllText((Join-Path $Root 'reorder-00-opened.xml'), $hierarchy, [Text.Encoding]::UTF8) |
| 23 | [xml]$tree = $hierarchy |
| 24 | $manager = New-Object Xml.XmlNamespaceManager($tree.NameTable) |
| 25 | $manager.AddNamespace('one', $namespace) |
| 26 | $notebookNode = $tree.DocumentElement |
| 27 | $sections = @($notebookNode.SelectNodes('one:Section', $manager)) |
| 28 | if ($sections.Count -lt 3) { throw "Expected three root sections, found $($sections.Count)." } |
| 29 | $last = $sections[$sections.Count - 1] |
| 30 | [void]$notebookNode.RemoveChild($last) |
| 31 | [void]$notebookNode.InsertBefore($last, $sections[0]) |
| 32 | [IO.File]::WriteAllText((Join-Path $Root 'reorder-01-update.xml'), $tree.OuterXml, [Text.Encoding]::UTF8) |
| 33 | $app.UpdateHierarchy($tree.OuterXml, 1) |
| 34 | $app.GetHierarchy($notebookId, 4, [ref]$hierarchy, 1) |
| 35 | [IO.File]::WriteAllText((Join-Path $Root 'reorder-02-reordered.xml'), $hierarchy, [Text.Encoding]::UTF8) |
| 36 | $app.SyncHierarchy($notebookId) |
| 37 | $app.CloseNotebook($notebookId, $false) |
| 38 | $notebookId = '' |
| 39 | Copy-Item -Recurse (Join-Path $Root 'notebook') (Join-Path $Root 'notebook-reordered') |
| 40 | $app.OpenHierarchy((Join-Path $Root 'notebook'), '', [ref]$notebookId, 0) |
| 41 | $hierarchy = Read-Tree |
| 42 | [IO.File]::WriteAllText((Join-Path $Root 'reorder-03-reopened.xml'), $hierarchy, [Text.Encoding]::UTF8) |
| 43 | $app.CloseNotebook($notebookId, $false) |
| 44 | $notebookId = '' |
| 45 | } finally { |
| 46 | if ($notebookId) { $app.CloseNotebook($notebookId, $false) } |
| 47 | [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($app) |
| 48 | [GC]::Collect() |
| 49 | [GC]::WaitForPendingFinalizers() |
| 50 | } |