Private/ConvertTo-SFExternalIdPart.ps1

function ConvertTo-SFExternalIdPart {
    [CmdletBinding()]
    [OutputType([string])]
    param (
        [AllowNull()]
        $Value,

        [AllowNull()]
        [string]$Format,

        [Parameter(Mandatory)]
        [string]$ResourceType,

        [Parameter(Mandatory)]
        [string]$Field
    )

    if ($null -eq $Value) {
        throw "Resource type '$ResourceType' has no value for external ID field '$Field'."
    }

    if (($Value -is [System.Collections.IEnumerable] -and $Value -isnot [string]) -or
        $Value -is [System.Collections.IDictionary]) {
        throw "External ID field '$Field' on resource type '$ResourceType' must contain a scalar value."
    }

    $text = if (-not [string]::IsNullOrWhiteSpace($Format)) {
        $date = ConvertTo-SFDateTimeOffset -Value $Value
        $date.ToString($Format, [Globalization.CultureInfo]::InvariantCulture)
    }
    elseif ($Value -is [DateTimeOffset]) {
        $Value.ToString('o', [Globalization.CultureInfo]::InvariantCulture)
    }
    elseif ($Value -is [DateTime]) {
        $Value.ToString('o', [Globalization.CultureInfo]::InvariantCulture)
    }
    elseif ($Value -is [IFormattable]) {
        $Value.ToString($null, [Globalization.CultureInfo]::InvariantCulture)
    }
    else {
        [string]$Value
    }

    if ([string]::IsNullOrWhiteSpace($text)) {
        throw "Resource type '$ResourceType' has an empty value for external ID field '$Field'."
    }

    return $text
}