Public/Export-GhostTag.ps1

function Export-GhostTag {
    <#
    .SYNOPSIS
        Writes the tags of the Ghost site to files, one per tag.

    .DESCRIPTION
        Saves every tag of the site as a file that Sync-GhostTag reads, so that tags 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 tag becomes <slug>.md in the folder. The file starts with front matter that holds the name of the tag
        and every other field that has a value, and the description of the tag is the text below it:

            ---
            name: "Release notes"
            accent_color: "#ff5500"
            ---

            What changed, version by version.

        A file that is the same as the tag 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 tag is no longer on the
        site is not removed.

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

    .EXAMPLE
        Export-GhostTag -Path ./tags

        Writes a file for every tag of the site that has none yet in the folder tags.

    .EXAMPLE
        Export-GhostTag -Path ./tags -Force

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

    .EXAMPLE
        Export-GhostTag -Path ./tags -Filter 'visibility:public'

        Writes the public tags only.

    .LINK
        https://docs.ghost.org/admin-api

    .LINK
        https://docs.ghost.org/content-api/tags
    #>

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

        # Which tags, as a filter of Ghost, such as visibility:public. Defaults to every tag.
        [string] $Filter,

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

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

        # The order of the front matter. The slug is the name of the file, the description the text below.
        $keys = @(
            'name', 'visibility', 'accent_color', 'feature_image', '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')
        }

        $query = @{}
        if ($Filter) {
            $query['Filter'] = $Filter
        }

        foreach ($tag in @(Get-GhostTag @query -Order 'slug asc')) {
            $lines = [System.Collections.Generic.List[string]]::new()
            $lines.Add('---')
            foreach ($key in $keys) {
                $property = $tag.PSObject.Properties[$key]
                $value = if ($property) { [string] $property.Value } else { '' }
                if (-not $value) {
                    continue
                }
                # Ghost derives the visibility from the name; it is only written when it says something else.
                $derived = if ($tag.name.StartsWith('#')) { 'internal' } else { 'public' }
                if ($key -eq 'visibility' -and $value -eq $derived) {
                    continue
                }
                $lines.Add(('{0}: {1}' -f $key, (& $quote $value)))
            }

            $property = $tag.PSObject.Properties['description']
            $description = if ($property) { [string] $property.Value } else { '' }
            $body = ($description -replace '\r\n?', "`n")
            if ($body -and ($body -cne $description -or $body -cne $body.Trim())) {
                # Text that would not come back the same from below the front matter goes in it.
                $lines.Add(('description: {0}' -f (& $quote $description)))
                $body = ''
            }
            $lines.Add('---')
            if ($body) {
                $lines.Add('')
                $lines.Add($body)
            }
            $content = ($lines -join "`n") + "`n"

            $file = Join-Path -Path $folder -ChildPath ('{0}.md' -f $tag.slug)
            $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 tag '$($tag.slug)'. Pass -Force to overwrite it."
                }
            }

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

            [pscustomobject]@{
                PSTypeName = 'Ghost.TagSync'
                Action     = $action
                Name       = $tag.name
                Slug       = $tag.slug
                Id         = $tag.id
                Path       = $file
            }
        }
    }
    catch {
        $PSCmdlet.ThrowTerminatingError($_)
    }
}