jsonpowershellscriptingonenoteonenote-api

PowerShell script/command to export OneNote page names + URLs to JSON


For all OneNote notebooks that are syncing to my Win10 PC, how can I use PowerShell to generate a .json file that contains an array of objects, where each object contains:

...for every OneNote notebook/section/page in my current Windows user login?

The output would look like:

    [
      {
        "notebook_name": "My Notebook name",
        "section_name": "The name of a section",
        "page_name": "The name of a page",
        "page_url": "onenote:https://d.docs.live.net/...etc..."
      },
      { /* ...etc...*/ }
    ]

Solution

  • I got a bit bored waiting on the OP, so here goes:

    $oneNote = New-Object -ComObject OneNote.Application
    [xml]$hierarchy = ""
    $oneNote.GetHierarchy("", [Microsoft.Office.InterOp.OneNote.HierarchyScope]::hsPages, [ref]$hierarchy)
    
    $result = foreach ($notebook in $hierarchy.Notebooks.Notebook ) {
        foreach ($section in $notebook.Section) {
            $sectionUrl = 'onenote:{0}' -f $section.path
            $section.ChildNodes | ForEach-Object { 
                [PsCustomObject]@{
                    'notebook_name' = $notebook.name
                    'section_name'  = $section.name
                    'page_name'     = $_.name
                    'page_url'      = '{0}/pages/{1}' -f $sectionUrl, $_.ID
                }
            }
        }
    }
    
    # clean up the COM object
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($oneNote) | Out-Null
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()
    
    $result | ConvertTo-Json