Get Domain from URL in Powershell

前端 未结 3 2030
旧时难觅i
旧时难觅i 2021-01-01 12:24

I\'m looking to strip out the domain in this scenario using PowerShell. What is the most effective method to get \'domain.com\' out of the following variable?



        
相关标签:
3条回答
  • 2021-01-01 13:05

    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))
    }
    
    0 讨论(0)
  • 2021-01-01 13:24

    Try the Uri class:

    PS> [System.Uri]"http://www.domain.com/folder/"
    
    
    AbsolutePath   : /folder/
    AbsoluteUri    : http://www.domain.com/folder/
    LocalPath      : /folder/
    Authority      : www.domain.com
    HostNameType   : Dns
    IsDefaultPort  : True
    IsFile         : False
    IsLoopback     : False
    PathAndQuery   : /folder/
    Segments       : {/, folder/}
    IsUnc          : False
    Host           : www.domain.com
    Port           : 80
    Query          :
    Fragment       :
    Scheme         : http
    OriginalString : http://www.domain.com/folder/
    DnsSafeHost    : www.domain.com
    IsAbsoluteUri  : True
    UserEscaped    : False
    UserInfo       :
    

    And remove the www prefix:

    PS> ([System.Uri]"http://www.domain.com/folder/").Host -replace '^www\.'
    domain.com
    
    0 讨论(0)
  • 2021-01-01 13:27

    Like this:

    PS C:\ps> [uri]$URL = "http://www.domain.com/folder/"
    PS C:\ps> $domain = $url.Authority -replace '^www\.'
    PS C:\ps> $domain
    domain.com
    
    0 讨论(0)
提交回复
热议问题