Skip to content

Instantly share code, notes, and snippets.

@JohnLBevan
Last active October 16, 2023 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JohnLBevan/5facbcd4eb0d3185ed0939935339b532 to your computer and use it in GitHub Desktop.
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..
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