Private/Save-GhostImage.ps1

function Save-GhostImage {
    <#
    .SYNOPSIS
        Fetches an image from its address and writes it to a file.

    .DESCRIPTION
        Export-GhostPost and Export-GhostPage use this to keep the images of a post or a page next to its file.
        A site shows its images to everybody, so the request carries no key.

        The file is written once all of the image is there, so that a request that fails leaves no half file
        behind. The folder of the file is created when it is not there. An answer without content is an error,
        and so is a page of HTML, which some hosts send for an image that is gone.

    .EXAMPLE
        Save-GhostImage -Url 'https://example.com/content/images/2026/11/diagram.png' -Path $file

        Writes the image to the file.
    #>

    [CmdletBinding()]
    [OutputType([void])]
    param(
        # The address of the image.
        [Parameter(Mandatory)]
        [string] $Url,

        # Full path of the file to write.
        [Parameter(Mandatory)]
        [string] $Path
    )

    # The progress bar of Invoke-WebRequest slows Windows PowerShell down considerably.
    $ProgressPreference = 'SilentlyContinue'

    Write-Verbose -Message "GET $Url"
    $response = Invoke-WebRequest -Uri $Url -Method 'Get' -UseBasicParsing -TimeoutSec 100 -ErrorAction 'Stop'

    # The content as it was sent. The property Content is text for some types of image, such as SVG.
    $bytes = $response.RawContentStream.ToArray()
    $type = [string] (@($response.Headers['Content-Type']) | Select-Object -First 1)
    if ($bytes.Length -eq 0) {
        throw "The address $Url answered with no content."
    }
    if ($type -match '^\s*text/html') {
        throw "The address $Url answered with a page instead of an image."
    }

    [System.IO.Directory]::CreateDirectory([System.IO.Path]::GetDirectoryName($Path)) | Out-Null
    [System.IO.File]::WriteAllBytes($Path, $bytes)
}