I am trying to open a OneNote file (could be a file on a network share, not necessarily my own OneNote file) using Powershell. I get an error
Exception calling "OpenHierarchy" with "4" argument(s): "Exception from HRESULT: 0x80042018"
on the call to OpenHierarchy and I could not find how to work around this. Can anyone help? Here is my code:
$OneNote = New-Object -ComObject OneNote.Application
$OneNoteFilePath = "someNetworkPath"
[ref]$xml = ""
[xml]$Hierarchy = ""
$OneNote.OpenHierarchy($OneNoteFilePath, "", $xml, "cftNotebook")
$OneNote.GetHierarchy("", [Microsoft.Office.InterOp.OneNote.HierarchyScope]::hsPages, [ref]$Hierarchy)
ForEach($notebook in $Hierarchy.Notebooks.Notebook)
{
[ref]$PageXML = ''
$OneNote.GetPageContent($notebook.ID, [ref]$PageXML, [Microsoft.Office.Interop.OneNote.PageInfo]::piAll)
If ($PageXML | Where-Object { $_ -match "\b$word\b" })
{
## Do something
}
ForEach($section in $notebook.Section)
{
[ref]$PageXML = ''
$OneNote.GetPageContent($notebook.ID, [ref]$PageXML, [Microsoft.Office.Interop.OneNote.PageInfo]::piAll)
If ($PageXML | Where-Object { $_ -match "\b$word\b" })
{
## Do something
}
}
}
There's a problem with the line:
$OneNote.OpenHierarchy($OneNoteFilePath, "", $xml, "cftNotebook")
The last parameter is supposed to be an int, 3, not a string "cftNotebook".
Or you can use the correct enumeration instead of 3: [Microsoft.Office.Interop.OneNote.CreateFileType]::cftSection
https://learn.microsoft.com/en-us/office/client-developer/onenote/application-interface-onenote https://learn.microsoft.com/en-us/office/client-developer/onenote/enumerations-onenote-developer-reference#odc_CreateFileType
If you are looking for a working snippet, here's something to get you started:
$OneNote = New-Object -ComObject OneNote.Application
$OneNoteFilePath = "c:\path\to\onenote.one"
[ref]$oneNoteID = ""
[xml]$Hierarchy = ""
$OneNote.OpenHierarchy($OneNoteFilePath, "", $oneNoteID, [Microsoft.Office.Interop.OneNote.CreateFileType]::cftSection)
$OneNote.GetHierarchy($oneNoteID.Value, [Microsoft.Office.InterOp.OneNote.HierarchyScope]::hsPages, [ref]$Hierarchy)
#At this point, check $Heirarchy for what properties it has, it could be Notebooks, or SectionGroup, or Section
#If your $Hierarchy contains sections, you can do this
ForEach($page in $Hierarchy.Section.Page)
{
[ref]$PageXML = ''
$OneNote.GetPageContent($page.ID, [ref]$PageXML, [Microsoft.Office.Interop.OneNote.PageInfo]::piAll)
Write-Output $PageXML.Value
}
Note that some sections can have section groups, in which case, you'll have to use some recursion.