【问题标题】:Need to Trim a url in powershell script需要在powershell脚本中修剪一个url
【发布时间】:2018-11-02 17:24:45
【问题描述】:

我有一个 URL www.example.com:1234/,我需要在上面修剪成 2 个变量:

  1. example.com
  2. 00234
    • 端口的第一位将替换为00

这可以在 PowerShell 中实现吗?

【问题讨论】:

    标签: powershell url


    【解决方案1】:

    这是一种方法... [grin]

    # fake reading in a list of URLs
    #    in real life, use Get-Content
    $UrlList = @'
    www.example.com:1234/
    www3.example.net:9876
    www.other.example.org:5678/
    '@ -split [environment]::NewLine
    
    $Regex = '^www.*?\.(?<Domain>.+):(?<Port>\d{1,}).*$'
    
    $Results = foreach ($UL_Item in $UrlList)
        {
        $Null = $UL_Item -match $Regex
    
        [PSCustomObject]@{
            URL = $UL_Item
            Domain = $Matches.Domain
            OriginalPort = $Matches.Port
            Port = '00{0}' -f (-join $Matches.Port.ToString().SubString(1))
            }
        }
    
    $Results
    

    输出...

    URL                        Domain           OriginalPort Port 
    ---                        ------           ------------ ---- 
    www.example.com:1234/     example.com     1234         00234
    www3.example.net:9876      example.net      9876         00876
    www.other.example.org:5678/ other.example.org 5678         00678    
    

    注释掉或删除任何不需要的属性。 [咧嘴一笑]


    根据要求,简化版本... [grin]

    $UserInput = 'www.example.com:1234/'
    
    $Regex = '^www.*?\.(?<Domain>.+):(?<Port>\d{1,}).*$'
    
    $Null = $UserInput -match $Regex
    
    $Domain = $Matches.Domain
    $Port = '00{0}' -f (-join $Matches.Port.SubString(1))
    
    $Domain
    $Port
    

    输出...

    example.com
    00234
    

    希望对你有帮助,

    【讨论】:

      【解决方案2】:
      [uri]$url = 'www.example.com:1234/'
      
      $Value1 = ($url.Scheme).Replace('www.','')
      $Value2 = "00" + ($url.AbsolutePath).Substring(1).TrimEnd('/')
      

      【讨论】:

        【解决方案3】:

        提供对James C.'s answer的改进:

        # Input URL string
        $urlText = 'www.example.com:1234/'
        
        # Prepend 'http://' and cast to [uri] (System.Uri), which
        # parses the URL string into its constituent components.
        $urlObj = [uri] "http://$urlText"
        
        # Extract the information of interest
        $domain = $urlObj.Host -replace '^www\.' # -> 'example.com'
        $modifiedPort = '00' + $urlObj.Port.ToString().Substring(1) # -> '00234'
        

        【讨论】:

        • 好 ole rfc2606 ;)
        猜你喜欢
        • 1970-01-01
        • 2018-08-08
        • 1970-01-01
        • 1970-01-01
        • 2011-12-29
        • 2022-01-23
        • 2015-05-18
        • 2023-03-03
        • 2014-01-21
        相关资源
        最近更新 更多