Functions/WriteHosts.ps1

using namespace System.Text;

function Write-Hosts {

    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [BaseRecord[]] $Records
    )

    # Render new hosts file content
    $hostsContentBuilder = [StringBuilder]::new();
    $hostRecordPrevious = $null;

    foreach ($hostRecord in $Records) {

        if ($hostRecord -is [EmptyRecord] -and
            $hostRecordPrevious -is [EmptyRecord]) {

            # Remove trailing empty records
            continue;
        }

        if ($null -ne $hostRecordPrevious) {
            
            # Start every record with new line
            [void]$hostsContentBuilder.AppendLine();
        }

        if ($hostRecord -is [CommentRecord] -and
            $hostRecordPrevious -is [HostRecord]) {
        
            # Add an extra empty line before a new group of records
            [void]$hostsContentBuilder.AppendLine();
        }

        [void]$hostsContentBuilder.Append($hostRecord);

        # Keep previous record
        $hostRecordPrevious = $hostRecord;
    }

    Set-Content -Path $HostsLocation -Value $hostsContentBuilder.ToString() -NoNewline;
}