Private/ConvertTo-GhostPostFile.ps1

function ConvertTo-GhostPostFile {
    <#
    .SYNOPSIS
        Returns the text of the Markdown file that describes a post or a page of the site.

    .DESCRIPTION
        Export-GhostPost and Export-GhostPage use this to write a file that Sync-GhostPost or Sync-GhostPage
        reads as the same post or page.

        The file starts with front matter that holds the title and every other field that has a value: the
        status, the tags, the excerpt, the images, the template and the fields for search engines. A visibility
        of public and the authors are left out. The slug is left out as well, because the name of the file or
        of its folder holds it.

        The content follows the front matter:

        - A post that was written as Markdown, in one or more Markdown cards, gives that Markdown back.
        - Any other post gives the HTML that Ghost renders for it, rewritten by ConvertTo-MarkdownHtmlBlock so
          that a Markdown card shows it as it is.

        The file has line feeds as line endings and ends with one.

    .EXAMPLE
        ConvertTo-GhostPostFile -Post (Get-GhostPost -Slug 'my-post' -Formats lexical, html -Include tags)

        Returns the text of the file for that post, and whether its content was Markdown, Html or Empty.
    #>

    [CmdletBinding()]
    [OutputType([pscustomobject])]
    param(
        # The post or the page, read with the formats lexical and html and with its tags.
        [Parameter(Mandatory)]
        [object] $Post
    )

    # The text fields, in the order of the front matter.
    $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 }
    }

    $lines = [System.Collections.Generic.List[string]]::new()
    $lines.Add('---')
    $lines.Add(('title: {0}' -f (& $quote ([string] $Post.title))))
    $lines.Add(('status: {0}' -f $Post.status))

    $visibility = [string] (& $read $Post 'visibility')
    if ($visibility -and $visibility -ne 'public') {
        $lines.Add(('visibility: {0}' -f (& $quote $visibility)))
    }
    if ((& $read $Post 'featured') -eq $true) {
        $lines.Add('featured: true')
    }
    $tags = @(& $read $Post '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 $Post '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 $Post $key)
        if ($value) {
            $lines.Add(('{0}: {1}' -f $key, (& $quote $value)))
        }
    }
    $lines.Add('---')

    # The content: the Markdown of the post when it is made of Markdown cards, its HTML otherwise.
    $kind = 'Empty'
    $body = ''
    $children = $null
    $lexical = [string] (& $read $Post 'lexical')
    if ($lexical) {
        try {
            $children = @((ConvertFrom-Json -InputObject $lexical).root.children | Where-Object { $_ })
        }
        catch {
            Write-Debug -Message "The content 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 = ConvertTo-MarkdownHtmlBlock -Html ([string] (& $read $Post 'html'))
        if ($html) {
            $kind = 'Html'
            $body = $html
        }
    }
    $body = ($body -replace '\r\n?', "`n").Trim("`n")
    if ($body) {
        $lines.Add('')
        $lines.Add($body)
    }

    [pscustomobject]@{
        Text    = ($lines -join "`n") + "`n"
        Content = $kind
    }
}