简体   繁体   English

需要在powershell脚本中修剪网址

[英]Need to Trim a url in powershell script

I have a URL www.example.com:1234/ and I need to trim above in to 2 variables: 我有一个URL www.example.com:1234/ ,我需要修改上面的2个变量:

  1. example.com
  2. 00234
    • first digit of port will be replaced by 00 端口的第一个数字将被00替换

Can this be achieved in PowerShell? 这可以在PowerShell中实现吗?

[uri]$url = 'www.example.com:1234/'

$Value1 = ($url.Scheme).Replace('www.','')
$Value2 = "00" + ($url.AbsolutePath).Substring(1).TrimEnd('/')

here's one way to do it ... [ 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

output ... 输出......

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    

comment out or delete any unwanted properties. 注释掉或删除任何不需要的属性。 [ grin ] [ ]


per request, a simplified version ... [ 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

output ... 输出......

example.com
00234

hope that helps, 希望有所帮助,
lee 背风处

To offer an improvement to James C.'s answer : James C.的回答提供改进:

# 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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM