public/Build-SfAddressSettingsMetadata.ps1

function Build-SfAddressSettingsMetadata {

    <#
        .SYNOPSIS
        Builds the Address.settings-meta.xml files from the State and Country picklist values in the metadata model.

        .DESCRIPTION
        Always builds the full TO BE state and country picklist data from the metadata model, without checking
        whether the target org's current Address Settings already contain all listed states and countries.
        Deploying a file with entries not yet present in the target org will fail, since the Metadata API cannot
        create new states or countries - use Compare-SfAddressSettingsDelta beforehand to identify missing entries.

        If -Manifest is supplied, the file is only built when it contains 'Settings:Address'; all other manifest
        entries are ignored. If -Manifest is omitted, the file is always built.

        .LINK
        https://codeberg.org/uwe-braig/sf-metadata-toolkit
    #>


    [CmdletBinding()]
    param (
        # The metadata model as imported from *.csv and/or *.xlsx with Import-SfMetadataModel
        [Parameter(Mandatory, Position = 0)]
        [PSCustomObject] $MetadataModel,

        # Manifest entries - only 'Settings:Address' is relevant, other Types are ignored.
        # If left empty, 'Settings:Address' will be assumed.
        [Parameter(ValueFromPipeline, Position = 1)]
        [string[]] $Manifest,

        # Target path for the resulting *.xml files. Default is [./force-app/main/default].
        [Parameter()]
        [string] $TargetPath = './force-app/main/default'
    )

    begin {
        $ErrorActionPreference = 'Stop'
        [bool] $IsDebug   = $DebugPreference   -ne 'SilentlyContinue'
        [bool] $IsVerbose = $VerbosePreference -ne 'SilentlyContinue'

        Write-Debug "Build-SfAddressSettingsMetadata|BEGIN"

        [int] $ReceivedCount = 0
        [bool] $HasAddressSettings = $false

        $SettingsPath = Join-Path $TargetPath 'settings'
    }

    process {
        foreach ($RawEntry in $Manifest) {
            $ReceivedCount++
            if ($RawEntry -eq 'Settings:Address') {
                $HasAddressSettings = $true
            }
        }
    }

    end {
        Write-Debug "Build-SfAddressSettingsMetadata|ReceivedCount=$ReceivedCount|HasAddressSettings=$HasAddressSettings"
        if ( ($ReceivedCount -eq 0) -or $HasAddressSettings ) {
            $xmlString = ConvertTo-SfCountriesAndStatesXml -MetadataModel $MetadataModel
            Set-MetadataXmlFile 'Settings' 'Address' '.settings-meta.xml' $SettingsPath $xmlString
        }
        Write-Debug "Build-SfAddressSettingsMetadata|END"
    }
}