Public/Sync-GhostPage.ps1

function Sync-GhostPage {
    <#
    .SYNOPSIS
        Creates or updates pages on the Ghost site from Markdown files.

    .DESCRIPTION
        Makes the page on the site match a Markdown file, which is what a pipeline needs to publish pages from a
        repository. A file starts with front matter between two lines of three dashes, followed by the Markdown
        of the page:

            ---
            title: My page
            tags: [News, Releases]
            custom_excerpt: Shown in lists
            ---

            # Heading

        The keys of the front matter are the fields of a page in the Ghost API, such as title, status, tags,
        custom_excerpt and feature_image. The parameter names of New-GhostPage, such as CustomExcerpt, work too.
        Front matter is YAML: text, true or false, lists, and text over several lines after | or >. A JSON object
        works as well, and is needed for a value inside a value, such as a tag with a description of its own.

        The slug identifies the page. It comes from the front matter or, without one there, from the name of the
        file: my-page.md is the page with the slug my-page. A file that is named index.md takes the name of its
        folder, so that a page can have a folder of its own, with its images next to it: my-page/index.md. A
        date at the start of the name, 2026-11-20-my-page, is not a part of the slug: it is the publication date
        of the page, unless the front matter has a published_at. A date without a time zone is read as UTC, so
        that the same file gives the same page on every machine.

        A page with that slug is updated; when there is none, the page is created, for which the front matter
        needs a title.

        A page is only updated when the file differs from the page, so the command can run for every file on
        every push. Fields that the front matter does not mention are left as they are on the site. The Markdown
        is stored as it is, in a Markdown card, and rendered by Ghost.

        The status in the front matter is followed: without one a new page is a draft and an existing page keeps
        its status, and "status": "published" publishes the page.

        A page that a route of the theme shows, with data: page.my-page in routes.yaml, has to exist before the
        route works: this is how such a page gets to every site that has the theme. Export-GhostPage writes
        these files from the pages of a site.

        An image can be a file next to the page. Refer to it by its path, relative to the folder of the Markdown
        file, in the Markdown, ![A diagram](images/diagram.png), or in the front matter as feature_image, og_image
        or twitter_image. The file is uploaded and the page gets its address. It is uploaded once: as long as the
        file does not change, the page keeps the image it has. An address (https://...) is left as it is. The
        addresses of the images that were uploaded are in the property UploadedImages of the result.

        Removing a file does not remove the page, unless PreviousPath says what the files were before. It holds
        the files as they were at the previous run, such as the previous commit of a repository. A page that a
        file there describes, and that no file in Path describes any more, is removed from the site. Pages are
        compared by their slug. A file that moved to another folder keeps its page. A file whose slug changed
        gives a new page, and the page with the old slug is removed. Removing cannot be undone, so the command
        asks for confirmation before it removes a page. Nothing is removed when a file in Path fails.

        An image that is no longer used stays on the site. Ghost cannot remove an image through its API.

        The property Action of a result says what was done: Created, Updated, Removed or Unchanged. With -WhatIf
        nothing is sent, and the action says what would be done: WouldCreate, WouldUpdate or WouldRemove. Such a
        result has the id of the page on the site when there is one, so do not pipe a dry run to a command that
        changes pages.

    .EXAMPLE
        Sync-GhostPage -Path ./pages

        Creates or updates a page for every .md file in the folder pages.

    .EXAMPLE
        Sync-GhostPage -Path ./pages -Recurse -WhatIf

        Returns which pages would be created or updated for the files in pages and the folders below it, such as
        pages/my-page/index.md. Nothing is sent.

    .EXAMPLE
        Sync-GhostPage -Path ./pages/about/index.md

        Creates or updates the page with the slug about.

    .EXAMPLE
        Sync-GhostPage -Path ./pages -Recurse -PreviousPath ./before/pages -Confirm:$false

        Creates or updates the pages, and removes every page that a file in before/pages describes and no file
        in pages describes any more. The folder before holds the previous commit, which git makes with
        git worktree add ./before HEAD~1.

    .LINK
        https://docs.ghost.org/admin-api/pages/creating-a-page

    .LINK
        https://docs.ghost.org/admin-api/pages/updating-a-page

    .LINK
        https://docs.ghost.org/admin-api/pages/deleting-a-page

    .LINK
        https://docs.ghost.org/admin-api/images/uploading-an-image
    #>

    [CmdletBinding(SupportsShouldProcess)]
    [OutputType('Ghost.PageSync')]
    param(
        # Markdown files, or folders of which every .md file is used, except a README.md. Wildcards are allowed.
        [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [Alias('FullName')]
        [ValidateNotNullOrEmpty()]
        [string[]] $Path,

        # Also use the .md files in the folders below a folder, for pages that have a folder of their own.
        [switch] $Recurse,

        # Files or folders with the files as they were at the previous run. A page that a file there describes,
        # and that no file in Path describes any more, is removed. Path has to name every current file then, so
        # this parameter cannot be used with files from the pipeline.
        [ValidateNotNullOrEmpty()]
        [string[]] $PreviousPath,

        # Update a page even when the file does not differ from it.
        [switch] $Force
    )

    begin {
        Test-GhostConnection
        Test-GhostPreviousPath -BoundParameters $PSBoundParameters

        # Everything a page can be given, except its content, which is the Markdown of the file, and the
        # updated_at value, which is taken from the page on the site.
        $body = (Get-GhostAPIData -Endpoint 'Set-GhostPage').Body
        $fields = @{}
        foreach ($name in $body.Keys) {
            if (@('Lexical', 'Html', 'UpdatedAt') -notcontains $name) {
                $fields[$name] = $body[$name]
            }
        }

        # The slugs of the files in Path. A page with one of these slugs is never removed.
        $slugs = [System.Collections.Generic.List[string]]::new()
    }

    process {
        foreach ($item in $Path) {
            foreach ($file in Get-GhostSyncFile -Path $item -Recurse:$Recurse) {
                try {
                    $source = Read-GhostPostFile -Path $file.FullName -Fields $fields
                    $slug = $source.Parameters['Slug']
                    $slugs.Add($slug)
                    $action = 'Unchanged'
                    $operation = $null
                    $dryRun = $false
                    $uploaded = @()

                    # Quoted, so that a slug of digits only is compared as text.
                    $result = @(Get-GhostPage -Filter "slug:'$slug'") | Select-Object -First 1

                    # The image files the page refers to. One that the page on the site already has, unchanged,
                    # comes with its address; the others are uploaded once it is certain that the page is saved.
                    $images = @(Get-GhostPostImage -Source $source -Post $result)
                    $pending = @($images | Where-Object { -not $_.Url })
                    $content = Convert-GhostPostImage -Source $source -Images $images
                    $page = $content.Parameters

                    if (-not $result) {
                        if ([string]::IsNullOrWhiteSpace([string] $page['Title'])) {
                            throw "There is no page with the slug '$slug' yet, and creating it needs a title."
                        }

                        $action = 'Created'
                        $operation = "Create the page '$slug'"
                    }
                    else {
                        $comparison = @{
                            Post       = $result
                            Parameters = $page
                            Fields     = $fields
                            Markdown   = $content.Markdown
                        }
                        # An image that has to be uploaded is a change by itself: it is new, or its file changed.
                        if ($Force -or $pending.Count -gt 0 -or (Test-GhostPostChange @comparison)) {
                            $action = 'Updated'
                            $operation = "Update the page '$slug'"
                        }
                    }

                    if ($operation) {
                        $count = @($pending | ForEach-Object { $_.Name } | Select-Object -Unique).Count
                        if ($count -gt 0) {
                            $noun = if ($count -eq 1) { 'image' } else { 'images' }
                            $operation = '{0} and upload {1} {2}' -f $operation, $count, $noun
                        }

                        $dryRun = -not $PSCmdlet.ShouldProcess($file.FullName, $operation)
                        if ($dryRun -and -not $WhatIfPreference) {
                            # The answer to the question was no. Nothing is done and nothing is reported.
                            continue
                        }
                    }

                    if ($operation -and -not $dryRun) {
                        foreach ($image in $pending) {
                            # Uploaded a moment ago, for an earlier reference to the same file.
                            if ($image.Url) {
                                continue
                            }

                            Write-Verbose -Message "Uploading $($image.Path) as $($image.Name)"
                            $upload = @{
                                Path      = $image.Path
                                Name      = $image.Name
                                Reference = $image.Destination
                            }
                            $imageUrl = (New-GhostImage @upload -Confirm:$false).url
                            $uploaded += $imageUrl
                            foreach ($other in $pending) {
                                if ($other.Name -ceq $image.Name) {
                                    $other.Url = $imageUrl
                                }
                            }
                        }
                        if ($pending.Count -gt 0) {
                            $content = Convert-GhostPostImage -Source $source -Images $images
                            $page = $content.Parameters
                        }

                        if ($action -eq 'Created') {
                            $result = New-GhostPage @page -Markdown $content.Markdown -Confirm:$false

                            if ($result.slug -cne $slug) {
                                # Ghost picks another slug when this one is taken, by a post for example. The
                                # page would not be found on the next run and be created again, so it is taken
                                # back.
                                Remove-GhostPage -Id $result.id -Confirm:$false
                                $stored = "Ghost cannot use the slug '$slug': it stored the page as"
                                $advice = 'The slug is probably taken by a post. Choose another slug.'
                                throw "$stored '$($result.slug)'. $advice"
                            }
                        }
                        else {
                            # The updated_at value of the page as it was just read: when somebody saves the page
                            # in between, Ghost refuses the update instead of overwriting that change.
                            $current = @{
                                Id        = $result.id
                                UpdatedAt = $result.updated_at
                            }
                            $result = Set-GhostPage @current @page -Markdown $content.Markdown -Confirm:$false
                        }
                    }

                    # What the result says about the page. Before a page is created there is nothing on the
                    # site to read, so the slug is that of the file.
                    $row = @{
                        Status = $null
                        Slug   = $slug
                        Title  = $null
                        Id     = $null
                        Url    = $null
                    }
                    if ($result) {
                        $row['Status'] = $result.status
                        $row['Slug'] = $result.slug
                        $row['Title'] = $result.title
                        $row['Id'] = $result.id
                        $url = $result.PSObject.Properties['url']
                        if ($url) {
                            $row['Url'] = $url.Value
                        }
                    }
                    if ($dryRun) {
                        # Nothing was saved. The file says what the page would be.
                        $action = if ($action -eq 'Created') { 'WouldCreate' } else { 'WouldUpdate' }
                        if ($page.ContainsKey('Title')) {
                            $row['Title'] = $page['Title']
                        }
                        if ($page.ContainsKey('Status')) {
                            $row['Status'] = $page['Status']
                        }
                        elseif (-not $result) {
                            $row['Status'] = 'draft'
                        }
                    }

                    [pscustomobject]@{
                        PSTypeName     = 'Ghost.PageSync'
                        Action         = $action
                        Status         = $row['Status']
                        Slug           = $row['Slug']
                        Title          = $row['Title']
                        Id             = $row['Id']
                        Url            = $row['Url']
                        Path           = $file.FullName
                        UploadedImages = @($uploaded)
                    }
                }
                catch {
                    # Says which file the error is about. An error from Ghost keeps its id, such as ValidationError,
                    # which is the part before the comma. A problem with the file itself was thrown as a message
                    # and has that message for an id.
                    $errorId = 'GhostPageFileError'
                    if ($_.FullyQualifiedErrorId -ne $_.Exception.Message) {
                        $errorId = $_.FullyQualifiedErrorId.Split(',')[0]
                    }

                    $message = '{0}: {1}' -f $file.FullName, $_.Exception.Message
                    $exception = [System.InvalidOperationException]::new($message, $_.Exception)
                    $record = [System.Management.Automation.ErrorRecord]::new(
                        $exception,
                        $errorId,
                        $_.CategoryInfo.Category,
                        $file.FullName
                    )
                    $PSCmdlet.ThrowTerminatingError($record)
                }
            }
        }
    }

    end {
        if ($PSBoundParameters.ContainsKey('PreviousPath')) {
            try {
                $removal = @{
                    Kind         = 'Page'
                    PreviousPath = $PreviousPath
                    CurrentSlug  = $slugs.ToArray()
                    Fields       = $fields
                    Recurse      = $Recurse
                }
                Remove-GhostSyncResource @removal
            }
            catch {
                $PSCmdlet.ThrowTerminatingError($_)
            }
        }
    }
}