Reputation: 121
I have a list of hostnames which have the domain and subdomian in the FQDN. I need to get only the parent (root) domain name from it.
I have tried with substring but have not succeeded.
abc.xyz.me.com
def.me.com
ghi.sub.new.com
jkl.sup.old.com
these are some examples and from the list and I would like to get the root domains (me,new,old).
Upvotes: 1
Views: 367
Reputation: 23355
Here's a solution that gets a unique list of the full parent domains into a variable named $ParentDomains
:
$Domains = 'abc.xyz.me.com', 'def.me.com', 'ghi.sub.new.com', 'jkl.sup.old.com'
$ParentDomains = $Domains | ForEach-Object {
$Domain = $_.Split('.')
$Domain[-2]+'.'+$Domain[-1]
} | Get-Unique
$ParentDomains
Explanation:
ForEach-Object
. Each domain in the loop is represented by $_
.[]
to get the second to last [-2]
and last [-1]
items in each array and outputs them as a new string separated by a '.'.Get-Unique
to remove duplicates.Upvotes: 1
Reputation: 7811
Split the string, reverse the array and then pull the second member
$list = @(
"abc.xyz.me.com",
"def.me.com",
"ghi.sub.new.com",
"jkl.sup.old.com"
)
$List | ForEach-Object {
[Array]::Reverse(($Arr = $_.Split(".")))
$TLD, $SLD, $Null = $Arr
$TLD # You're top level domain
$SLD # The second level domain
# The rest of the values after those two get sent to null land
}
Upvotes: 1
Reputation: 41
The simple way would be to use split and get the index of -2
$FQDN = ('abc.xyz.me.com', 'def.me.com', 'ghi.sub.new.com', 'jkl.sup.old.com')
ForEach ($Domain in $FQDN)
{
write-host ($Domain.split(".")[-2])
}
You probably want to do more than just write to host, but that should give you the idea.
Upvotes: 1