Public/Export-GhostPost.ps1
|
function Export-GhostPost { <# .SYNOPSIS Writes posts of the Ghost site to Markdown files, one folder per post. .DESCRIPTION Saves posts of the site as files that Sync-GhostPost reads, so that posts that were written in Ghost Admin can be kept in a repository and be given to another site, such as one on your own machine. A post becomes <date>-<slug>/index.md in the folder, where the date is the day the post was published, in UTC. A post without a publication date becomes <slug>/index.md. A post that a file in the folder, or in a folder below it, already describes keeps that file, whatever its name is. So a file can be moved or renamed after it was written, as long as its post keeps its slug. The file starts with front matter that holds the title of the post and every other field that has a value: its status, tags, publication date, excerpt, images, template and the fields for search engines. The authors are left out. The content of the post follows: - 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. Markdown may contain HTML, so Sync-GhostPost can send it to a site, where it is stored in a Markdown card. Such a post looks the same in most cases, but it is no longer made of the cards of the editor. The HTML is written without empty lines, because Markdown stops reading HTML at an empty line. An empty line in a code block is kept. The line break before it is written as a character reference, which a browser reads as that line break. The property Content of the result says which of the two a post was: Markdown, Html or Empty. The property Visibility says who may read the post on the site: public, members, paid or tiers. The file of a post holds all of its content, also when the site shows it to members only. An image is written as its address, and stays on the site it is on. With -IncludeImage the images that were uploaded to the site are saved as files as well. Those are the images with /content/images/ in their address. Such an image is fetched from its address, which needs no key, and written in a folder images next to the file of the post. Its name is the path it has below /content/images/ with a hyphen for every slash, such as images/2026-11-diagram.png. The file of the post then has that path where the address was, in the content and as feature_image, og_image or twitter_image. That is how Sync-GhostPost reads an image file. The property SavedImages of the result has the files that were written. - An image that has its file already is not fetched again. - An image at any other address stays an address. So does an image that cannot be fetched, with a warning, and the next run tries it again. - An image in HTML loses its srcset and sizes, which hold addresses of the same image in other widths. A site then shows the image as it was uploaded. - Sync-GhostPost uploads an image file to the site it sends the post to. That is also true for the site the image came from, which then has it twice. Ghost cannot remove an image through its API. After that the post has the address of the upload, and an export writes the path of the file for it. A file that is the same as the post 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 post is no longer on the site is not removed. A file counts as the same as its post with its images as addresses and with its images as paths. With -IncludeImage a file with addresses is written again with the paths. A link to another page of the same site may be written without the address of the site, such as [text](/a-page/). Ghost gives it back with the address, and the file still counts as the same as its post. Writing such a file again would put the address in its links, so that only happens with -Force. When -IncludeImage has an image to save for such a file, the file is reported as Skipped. Pass a filter to write the posts that were made in Ghost Admin and no others. A post that came from a file can differ from what this command writes for it, in the fields of its front matter for one, and is then reported as Skipped. .EXAMPLE Export-GhostPost -Path ./posts -Filter 'tag:news' Writes a file for every post with the tag news that has none yet in the folder posts. .EXAMPLE Export-GhostPost -Path ./posts -Filter 'tag:hash-lesson+status:published' -Force Writes the published posts with the internal tag #lesson, and overwrites the files that differ from their post. The slug of an internal tag starts with hash- where its name starts with #. .EXAMPLE Export-GhostPost -Path ./posts -Filter 'tag:news' -IncludeImage Writes the posts with the tag news and saves their images next to them, such as ./posts/2026-11-20-my-post/images/2026-11-diagram.png. .EXAMPLE Export-GhostPost -Path ./posts Writes a file for every post of the site that has none yet. .LINK https://docs.ghost.org/admin-api/posts/overview #> [CmdletBinding(SupportsShouldProcess)] [OutputType('Ghost.PostSync')] param( # Folder for the posts. Created when it is not there. [Parameter(Mandatory, Position = 0)] [ValidateNotNullOrEmpty()] [string] $Path, # Which posts, as a filter of Ghost, such as tag:news or status:published. Defaults to every post. [string] $Filter, # Overwrite a file that differs from its post. [switch] $Force, # Also save the images that were uploaded to the site, in a folder images next to the file of the post, # and write each of them in the file as the path of its file. [switch] $IncludeImage ) try { Test-GhostConnection $folder = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path) # The fields a post file can set, to read a file the way Sync-GhostPost reads it. $body = (Get-GhostAPIData -Endpoint 'Set-GhostPost').Body $fields = @{} foreach ($name in $body.Keys) { if (@('Lexical', 'Html', 'UpdatedAt') -notcontains $name) { $fields[$name] = $body[$name] } } # The files that are there already, by the slug of their post. $files = @{} if (Test-Path -LiteralPath $folder -PathType Container) { foreach ($existing in Get-GhostSyncFile -Path $folder -Recurse) { try { $source = Read-GhostPostFile -Path $existing.FullName -Fields $fields } catch { Write-Warning -Message "A file that is not read as a post is left alone. $($_.Exception.Message)" continue } $slug = [string] $source.Parameters['Slug'] if (-not $files.ContainsKey($slug)) { $files[$slug] = $existing.FullName } } } $query = @{ Formats = 'lexical', 'html' Include = 'tags' Order = 'slug asc' } if ($Filter) { $query['Filter'] = $Filter } # The addresses of the site, to compare a link that a file has without them. $siteUrl = @(Get-GhostSiteUrl) foreach ($post in @(Get-GhostPost @query)) { $file = $files[[string] $post.slug] if (-not $file) { # A new file is named after the day of publication, which Sync-GhostPost does not take for a # part of the slug. A date is a [datetime] on PowerShell 7 and text on Windows PowerShell. $name = [string] $post.slug $day = $null $publishedAt = $post.PSObject.Properties['published_at'] if ($publishedAt -and $publishedAt.Value -is [datetime]) { $day = $publishedAt.Value.ToUniversalTime() } elseif ($publishedAt -and $publishedAt.Value) { $moment = [datetimeoffset]::MinValue $styles = [System.Globalization.DateTimeStyles]::AssumeUniversal $culture = [cultureinfo]::InvariantCulture if ([datetimeoffset]::TryParse([string] $publishedAt.Value, $culture, $styles, [ref] $moment)) { $day = $moment.UtcDateTime } } if ($day) { $name = '{0}-{1}' -f $day.ToString('yyyy-MM-dd', [cultureinfo]::InvariantCulture), $name } $file = Join-Path -Path (Join-Path -Path $folder -ChildPath $name) -ChildPath 'index.md' } # What the file needs: to be written, its images to be saved, or nothing. $comparison = @{ Post = $post Path = $file Fields = $fields IncludeImage = $IncludeImage Force = $Force SiteUrl = $siteUrl } $change = Compare-GhostPostFile @comparison $action = $change.Action $saved = @() if ($action -eq 'Skipped') { Write-Warning -Message "$file differs from the post '$($post.slug)'. Pass -Force to overwrite it." } elseif ($change.Write -or $change.Images.Count -gt 0) { $count = $change.Images.Count $noun = if ($count -eq 1) { 'image' } else { 'images' } $operation = "Write the post '$($post.slug)'" if ($count -gt 0 -and $change.Write) { $operation = '{0} and save {1} {2}' -f $operation, $count, $noun } elseif ($count -gt 0) { $operation = "Save {0} {1} of the post '{2}'" -f $count, $noun, $post.slug } if (-not $PSCmdlet.ShouldProcess($file, $operation)) { continue } $done = Save-GhostPostFile -Post $post -Change $change $action = $done.Action $saved = $done.SavedImages } $row = @{ Url = $null Visibility = $null } foreach ($name in 'url', 'visibility') { $property = $post.PSObject.Properties[$name] if ($property) { $row[$name] = $property.Value } } [pscustomobject]@{ PSTypeName = 'Ghost.PostSync' Action = $action Status = $post.status Slug = $post.slug Title = $post.title Id = $post.id Url = $row['Url'] Path = $file UploadedImages = @() Content = $change.Content Visibility = $row['Visibility'] SavedImages = @($saved) } } } catch { $PSCmdlet.ThrowTerminatingError($_) } } |