Private/ConvertTo-ApiValue.ps1
|
function ConvertTo-ApiValue { <# .SYNOPSIS Converts a parameter value to the form the Ghost Admin API expects. .DESCRIPTION Switches become booleans and dates become ISO 8601 timestamps in UTC, with the millisecond precision Ghost uses for updated_at. For a request body the value otherwise keeps its type, and an empty string becomes null so that a text field can be cleared. With -AsString the value is flattened to the text of a query string parameter: booleans in lower case and lists joined by commas. .EXAMPLE ConvertTo-ApiValue -Value (Get-Date) Returns a timestamp such as 2026-06-21T06:17:25.000Z. .EXAMPLE ConvertTo-ApiValue -Value 'authors', 'tags' -AsString Returns authors,tags. #> [CmdletBinding()] [OutputType([object], [object[]], [string])] param( # The parameter value to convert. [Parameter(Mandatory)] [AllowNull()] [AllowEmptyString()] [AllowEmptyCollection()] [object] $Value, # Return the text for a query string parameter instead of a value for a request body. [switch] $AsString ) if ($null -eq $Value) { return $null } if ($Value -is [switch]) { $Value = $Value.IsPresent } if ($Value -is [datetimeoffset]) { $Value = $Value.UtcDateTime } if ($Value -is [datetime]) { return $Value.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ', [cultureinfo]::InvariantCulture) } if (-not $AsString) { if ($Value -is [string] -and $Value.Length -eq 0) { return $null } # The comma keeps a list a list; without it PowerShell would unroll it on the way out. return , $Value } if ($Value -is [bool]) { return $Value.ToString().ToLowerInvariant() } if ($Value -is [System.Collections.IEnumerable] -and $Value -isnot [string]) { $items = foreach ($item in $Value) { ConvertTo-ApiValue -Value $item -AsString } return $items -join ',' } [System.Convert]::ToString($Value, [cultureinfo]::InvariantCulture) } |