Last active
October 16, 2023 13:59
-
-
Save JohnLBevan/5facbcd4eb0d3185ed0939935339b532 to your computer and use it in GitHub Desktop.
Get the root domain from a given subdomain; i.e. the first level under a public suffix / "top level domain" (TLD). So given the string "test.example.co.uk" this would return "example.co.uk", whilst "example.com" would return itself unchanged..
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ConvertTo-RootDomain { | |
[CmdletBinding()] | |
Param ( | |
[Parameter(Mandatory)] | |
[string]$Domain | |
) | |
if ($null -eq $Global:CachedPublicDomainSuffixList) { | |
$publicDomainSuffixList = Invoke-WebRequest -Method GET -Uri 'https://publicsuffix.org/list/public_suffix_list.dat' -ContentType 'text/plain' -ErrorAction Stop | |
$tempSet = [System.Collections.Generic.HashSet[string]]::new() | |
foreach ($suffix in @($publicDomainSuffixList.Content -split '\s*[\r\n]+')) { | |
if ($suffix -notlike '//*') { | |
$tempSet.Add($suffix) | Out-Null | |
} | |
} | |
$Global:CachedPublicDomainSuffixList = $tempSet | |
} | |
$domainPieces = $Domain -split '\.' | |
for ($i=1; $i -lt $domainPieces.Count; $i++) { | |
if ($Global:CachedPublicDomainSuffixList.Contains(($domainPieces[$i..$domainPieces.Count] -join '.'))) { | |
return ($domainPieces[($i-1)..$domainPieces.Count] -join '.') | |
} | |
} | |
return $Domain | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment