Get Domain from URL in Powershell

Like this:

PS C:\ps> [uri]$URL = "http://www.example.com/folder/"
PS C:\ps> $domain = $url.Authority -replace '^www\.'
PS C:\ps> $domain
example.com

For properly calculating the sub-domain, the trick is you need to know the second to last period. Then you take a substring of that second to last period (or none if it is only one .) to the final position by subtracting the location of second period (or 0) from total length of domain. This will return the proper domain-only and will work regardless of how many sub-domains are nested under the TLD:

$domain.substring((($domain.substring(0,$domain.lastindexof("."))).lastindexof(".")+1),$domain.length-(($domain.substring(0,$domain.lastindexof("."))).lastindexof(".")+1))

Also note that System URI itself is valid 99% of the time but I'm parsing my IIS logs and finding that with VERY long (often invalid/malicious requests) URIs it does not properly parse and fails those.

I have this in function form as:

Function Get-DomainFromURL {
    <#
    .SYNOPSIS
    Takes string URL and returns domain only
    .DESCRIPTION
    Takes string URL and returns domain only
    .PARAMETER URL
    URL to parse for domain
    .NOTES
    Author: Dane Kantner 9/16/2016

    #>

    [CmdletBinding()]
        param(
        [Alias("URI")][parameter(Mandatory=$True,ValueFromPipeline=$True)][string] $URL
    )

    try { $URL=([System.URI]$URL).host }
    catch { write-error "Error parsing URL"}
    return $URL.substring((($URL.substring(0,$URL.lastindexof("."))).lastindexof(".")+1),$URL.length-(($URL.substring(0,$URL.lastindexof("."))).lastindexof(".")+1))
}

Try the URI class:

PS> [System.Uri]"http://www.example.com/folder/"

AbsolutePath   : /folder/
AbsoluteUri    : http://www.example.com/folder/
LocalPath      : /folder/
Authority      : www.example.com
HostNameType   : Dns
IsDefaultPort  : True
IsFile         : False
IsLoopback     : False
PathAndQuery   : /folder/
Segments       : {/, folder/}
IsUnc          : False
Host           : www.example.com
Port           : 80
Query          :
Fragment       :
Scheme         : http
OriginalString : http://www.example.com/folder/
DnsSafeHost    : www.example.com
IsAbsoluteUri  : True
UserEscaped    : False
UserInfo       :

And remove the www prefix:

PS> ([System.Uri]"http://www.example.com/folder/").Host -replace '^www\.'
example.com

Tags:

Powershell