Public/Export-GhostPage.ps1

function Export-GhostPage {
    <#
    .SYNOPSIS
        Writes the pages of the Ghost site to Markdown files, one folder per page.

    .DESCRIPTION
        Saves every page of the site as a file that Sync-GhostPage reads, so that pages that were made in Ghost
        Admin can be kept in a repository and be given to another site, such as one on your own machine.

        A page becomes <slug>/index.md in the folder. The file starts with front matter that holds the title of
        the page and every other field that has a value: its status, tags, excerpt, images, template and the
        fields for search engines. The authors are left out. The content of the page follows:

        - A page that was written as Markdown, in one or more Markdown cards, gives that Markdown back.
        - Any other page gives the HTML that Ghost renders for it. Markdown may contain HTML, so Sync-GhostPage
          can send it to a site, where it is stored in a Markdown card. Such a page looks the same in most
          cases, but it is no longer made of the cards of the editor.

        The property Content of the result says which of the two a page was: Markdown, Html or Empty.

        An image is written as its address, and stays on the site it is on.

        A file that is the same as the page already is left alone. A file that differs is only overwritten with
        -Force; without it the file is reported as Skipped, with a warning. A file whose page is no longer on
        the site is not removed.

    .EXAMPLE
        Export-GhostPage -Path ./pages

        Writes a file for every page of the site that has none yet in the folder pages.

    .EXAMPLE
        Export-GhostPage -Path ./pages -Force

        Also overwrites the files that differ from their page: the folder becomes what the site has.

    .EXAMPLE
        Export-GhostPage -Path ./pages -Filter 'status:published'

        Writes the published pages only.

    .LINK
        https://docs.ghost.org/admin-api/pages/overview
    #>

    [CmdletBinding(SupportsShouldProcess)]
    [OutputType('Ghost.PageSync')]
    param(
        # Folder for the pages. Created when it is not there.
        [Parameter(Mandatory, Position = 0)]
        [ValidateNotNullOrEmpty()]
        [string] $Path,

        # Which pages, as a filter of Ghost, such as status:published. Defaults to every page.
        [string] $Filter,

        # Overwrite a file that differs from its page.
        [switch] $Force
    )

    try {
        Test-GhostConnection
        $folder = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)

        # The text fields, in the order of the front matter. The slug is the name of the folder.
        $keys = @(
            'custom_excerpt', 'feature_image', 'feature_image_alt', 'feature_image_caption', 'custom_template'
            'canonical_url', 'meta_title', 'meta_description', 'og_image', 'og_title', 'og_description'
            'twitter_image', 'twitter_title', 'twitter_description', 'codeinjection_head', 'codeinjection_foot'
        )
        # Text in double quotes can hold anything, once a backslash, a quote and the line ends are escaped.
        $quote = {
            param($Text)
            $escaped = $Text.Replace('\', '\\').Replace('"', '\"')
            '"{0}"' -f $escaped.Replace("`r", '\r').Replace("`n", '\n').Replace("`t", '\t')
        }
        # The value of a property that may not be there.
        $read = {
            param($Object, $Name)
            $property = $Object.PSObject.Properties[$Name]
            if ($property) { $property.Value }
        }

        $query = @{
            Formats = 'lexical', 'html'
            Include = 'tags'
            Order   = 'slug asc'
        }
        if ($Filter) {
            $query['Filter'] = $Filter
        }

        foreach ($page in @(Get-GhostPage @query)) {
            $lines = [System.Collections.Generic.List[string]]::new()
            $lines.Add('---')
            $lines.Add(('title: {0}' -f (& $quote ([string] $page.title))))
            $lines.Add(('status: {0}' -f $page.status))

            $visibility = [string] (& $read $page 'visibility')
            if ($visibility -and $visibility -ne 'public') {
                $lines.Add(('visibility: {0}' -f (& $quote $visibility)))
            }
            if ((& $read $page 'featured') -eq $true) {
                $lines.Add('featured: true')
            }
            $tags = @(& $read $page 'tags' | Where-Object { $_ } | ForEach-Object { & $quote ([string] $_.name) })
            if ($tags.Count -gt 0) {
                $lines.Add(('tags: [{0}]' -f ($tags -join ', ')))
            }
            # A date is a [datetime] on PowerShell 7 and text on Windows PowerShell.
            $publishedAt = & $read $page 'published_at'
            if ($publishedAt -is [datetime]) {
                $format = 'yyyy-MM-ddTHH:mm:ss.fffZ'
                $publishedAt = $publishedAt.ToUniversalTime().ToString($format, [cultureinfo]::InvariantCulture)
            }
            if ($publishedAt) {
                $lines.Add(('published_at: {0}' -f (& $quote ([string] $publishedAt))))
            }
            foreach ($key in $keys) {
                $value = [string] (& $read $page $key)
                if ($value) {
                    $lines.Add(('{0}: {1}' -f $key, (& $quote $value)))
                }
            }
            $lines.Add('---')

            # The content: the Markdown of the page when it is made of Markdown cards, its HTML otherwise.
            $kind = 'Empty'
            $body = ''
            $children = $null
            $lexical = [string] (& $read $page 'lexical')
            if ($lexical) {
                try {
                    $children = @((ConvertFrom-Json -InputObject $lexical).root.children | Where-Object { $_ })
                }
                catch {
                    Write-Debug -Message "The content of the page cannot be read: $($_.Exception.Message)"
                }
            }
            $other = @($children | Where-Object { $_ -and $_.type -ne 'markdown' })
            if ($null -ne $children -and $children.Count -gt 0 -and $other.Count -eq 0) {
                $kind = 'Markdown'
                $body = @($children | ForEach-Object { [string] $_.markdown }) -join "`n`n"
            }
            elseif ($null -eq $children -or $children.Count -gt 0) {
                $html = [string] (& $read $page 'html')
                if ($html) {
                    $kind = 'Html'
                    $body = $html
                }
            }
            $body = ($body -replace '\r\n?', "`n").Trim("`n")
            if ($body) {
                $lines.Add('')
                $lines.Add($body)
            }
            $content = ($lines -join "`n") + "`n"

            $directory = Join-Path -Path $folder -ChildPath $page.slug
            $file = Join-Path -Path $directory -ChildPath 'index.md'
            $action = 'Created'
            if (Test-Path -LiteralPath $file) {
                $existing = [System.IO.File]::ReadAllText($file, [System.Text.Encoding]::UTF8)
                if (($existing -replace '\r\n?', "`n") -ceq $content) {
                    $action = 'Unchanged'
                }
                elseif ($Force) {
                    $action = 'Updated'
                }
                else {
                    $action = 'Skipped'
                    Write-Warning -Message "$file differs from the page '$($page.slug)'. Pass -Force to overwrite it."
                }
            }

            if (@('Created', 'Updated') -contains $action) {
                if (-not $PSCmdlet.ShouldProcess($file, "Write the page '$($page.slug)'")) {
                    continue
                }
                New-Item -Path $directory -ItemType Directory -Force | Out-Null
                [System.IO.File]::WriteAllText($file, $content, [System.Text.UTF8Encoding]::new($false))
            }

            [pscustomobject]@{
                PSTypeName     = 'Ghost.PageSync'
                Action         = $action
                Status         = $page.status
                Slug           = $page.slug
                Title          = $page.title
                Id             = $page.id
                Url            = & $read $page 'url'
                Path           = $file
                UploadedImages = @()
                Content        = $kind
            }
        }
    }
    catch {
        $PSCmdlet.ThrowTerminatingError($_)
    }
}