簡體   English   中英

需要在powershell腳本中修剪網址

[英]Need to Trim a url in powershell script

我有一個URL www.example.com:1234/ ,我需要修改上面的2個變量:

  1. example.com
  2. 00234
    • 端口的第一個數字將被00替換

這可以在PowerShell中實現嗎?

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

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

這是一種方法... [ ]

# 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    

注釋掉或刪除任何不需要的屬性。 [ ]


根據要求,簡化版...... [ ]

$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

希望有所幫助,
背風處

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