Private/Get-GhostUploadedImage.ps1

function Get-GhostUploadedImage {
    <#
    .SYNOPSIS
        Tells whether an address is that of an image that was uploaded to a Ghost site, and names a file for it.

    .DESCRIPTION
        Ghost keeps an uploaded image below /content/images/, on the site itself or on the storage of its host:
        https://example.com/content/images/2026/11/diagram.png. For such an address this returns the address to
        fetch the image from and the name of a file to keep it in. For any other address it returns nothing,
        and so it does for a type of image that New-GhostImage cannot upload again as the image of a post.

        Ghost serves an image in other widths and formats as well, at an address with /size/w600/ or
        /format/webp/ in it. The address that is returned is that of the image as it was uploaded.

        The name is the path below /content/images/ with a hyphen for every slash: 2026-11-diagram.png. Ghost
        gives every upload a path of its own, so two images of a site do not get the same name. Every character
        that is not a letter, a digit, a dot, an underscore or a hyphen becomes a hyphen, so that the name can
        be written in Markdown and in HTML as it is.

    .EXAMPLE
        Get-GhostUploadedImage -Url 'https://example.com/content/images/size/w600/2026/11/diagram.png'

        Returns the address https://example.com/content/images/2026/11/diagram.png and the name
        2026-11-diagram.png.
    #>

    [CmdletBinding()]
    [OutputType([pscustomobject])]
    param(
        # The address, as a post has it.
        [Parameter(Mandatory)]
        [AllowEmptyString()]
        [string] $Url
    )

    $pattern = '^(?<base>https?://[^/?#\s]+(?:/[^?#\s]*?)?/content/images/)(?<path>[^?#\s]+)(?:[?#]\S*)?$'
    $match = [regex]::Match($Url, $pattern, [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
    if (-not $match.Success) {
        return
    }

    # Without the folders of another width and another format.
    $path = $match.Groups['path'].Value -replace '^(?:size/[^/]+/)?(?:format/[^/]+/)?', ''
    try {
        $name = [uri]::UnescapeDataString($path)
    }
    catch {
        Write-Debug -Message "'$path' cannot be decoded: $($_.Exception.Message)"
        $name = $path
    }
    $name = ($name -replace '[^A-Za-z0-9._-]+', '-').Trim('-')

    # The types that Ghost takes as the image of a post.
    $types = '.gif', '.jpeg', '.jpg', '.png', '.svg', '.svgz', '.webp'
    $extension = [System.IO.Path]::GetExtension($name)
    if ($types -notcontains $extension -or $name.Length -le $extension.Length) {
        return
    }

    [pscustomobject]@{
        Url  = $match.Groups['base'].Value + $path
        Name = $name
    }
}