Functions/ReadHosts.ps1


$HostsLinePattern = '^\s*(?:(?<comment>#.*?)||(?<address>[:\d.]+)\s+(?<names>.+?))\s*$';

function Read-Hosts {

    foreach ($hostsRecord in Get-Content $HostsLocation) {

        $recordMathed = $hostsRecord -match $HostsLinePattern;

        if ($false -eq $recordMathed) {
            
            # Skip records we can't parse
            continue;
        }

        if ($matches.comment) {

            $record = [CommentRecord]::new();
            $record.Comment = $matches.comment;
        }
        elseif ($matches.address -and $matches.names) {

            $record = [HostRecord]::new();
            $record.Address = $matches.address;
            $record.Names = $matches.names -split '\s+';
        }
        else {

            $record = [EmptyRecord]::new();
        }

        Write-Output $record;
    }
}