在PowerShell中使用分隔符连接部件的最佳方式



我需要将多个Url元素连接到一个字符串中,所以我编写了通用的join-Parts函数:

filter Skip-Null { $_|?{ $_ } }
function Join-Parts
{
    param
    (
        $Parts = $null,
        $Separator = ''
    )
    [String]$s = ''
    $Parts | Skip-Null | ForEach-Object {
        $v = $_.ToString()
        if ($s -ne '')
        {
            if (-not ($s.EndsWith($Separator)))
            {
                if (-not ($v.StartsWith($Separator)))
                {
                    $s += $Separator
                }
                $s += $v
            }
            elseif ($v.StartsWith($Separator))
            {
                $s += $v.SubString($Separator.Length)
            }
        }
        else
        {
            $s = $v
        }
    }
    $s
}
Join-Parts -Separator '/' -Parts 'http://mysite','sub/subsub','/one/two/three'
Join-Parts -Separator '/' -Parts 'http://mysite',$null,'one/two/three'
Join-Parts -Separator '/' -Parts 'http://mysite','','/one/two/three'
Join-Parts -Separator '/' -Parts 'http://mysite/','',$null,'/one/two/three'
Join-Parts 1,2,'',3,4

如预期返回:

http://mysite/sub/subsub/one/two/three
http://mysite/one/two/three
http://mysite/one/two/three
http://mysite/one/two/three
1234

我觉得这不是最聪明的方法。有什么更好的方法吗?

更新

根据@sorens的回答,我将函数改为:

function Join-Parts
{
    param
    (
        $Parts = $null,
        $Separator = ''
    )
    ($Parts | ? { $_ } | % { ([string]$_).trim($Separator) } | ? { $_ } ) -join $Separator 
}

基于@mjolinor的答案,这一行通过了问题中的所有测试:

($parts | ? { $_ } | % { ([string]$_).trim('/') } | ? { $_ } ) -join '/' 

如果您并不真正关心最后一个测试用例(1,2,'',3,4),并且可以假设所有输入都是字符串,则可以将其缩短为:

($parts | ? { $_ } | % { $_.trim('/') } | ? { $_ } ) -join '/' 

请注意,我有两个null/empty过滤器(? { $_ } ):第一个从输入中去除null或空字符串,它用空字符串('http:/fdfdfddf','','aa/bb')纠正您的测试用例。第二个也是必要的,捕获输入通过修剪功能减少为空。

如果你真的想挑剔它,你应该再添加一个修剪来消除只包含空白的值,因为这些值可能是不需要的:

($parts | ? { $_ } | % { $_.trim('/').trim() } | ? { $_ } ) -join '/' 

对于最后一个,这些测试用例输入也将返回http://mysite/one/two:

$parts = 'http://mysite',''     ,'one/two' # empty
$parts = 'http://mysite','     ','one/two' # whitespace
$parts = 'http://mysite','    /','one/two' # trailing virgule
$parts = 'http://mysite','/    ','one/two' # leading virgule
$parts = 'http://mysite','/   /','one/two' # double virgule

您可以这样做:

($parts | foreach {$_.trim('/'))} -join '/'

下面是一个使用UriBuilder类创建URL的示例:

$builder = New-Object System.UriBuilder
$builder.Host = "www.myhost.com"
$builder.Path = ('folder', 'subfolder', 'page.aspx' -join '/')
$builder.Port = 8443
$builder.Scheme = 'https'
$builder.ToString()

输出:

https://www.myhost.com:8443/folder/subfolder/page.aspx

更新-这里有一个小功能,应该能够组合你的URL部分:

function Join-Parts {
    param ([string[]] $Parts, [string] $Seperator = '')
    $search = '(?<!:)' + [regex]::Escape($Seperator) + '+'  #Replace multiples except in front of a colon for URLs.
    $replace = $Seperator
    ($Parts | ? {$_ -and $_.Trim().Length}) -join $Seperator -replace $search, $replace
}
Join-Parts ('http://mysite','sub/subsub','/one/two/three') '/'
Join-Parts ('http://mysite',$null,'one/two/three') '/'
Join-Parts ('http://mysite','','/one/two/three') '/'
Join-Parts (1,2,'',3,4) ','

输出:

http://mysite/sub/subsub/one/two/three
http://mysite/one/two/three
http://mysite/one/two/three
1,2,3,4

从Path的顶部答案中汲取灵感。合并URL?

function Combine-UriParts ($base, $path)
{
    return [Uri]::new([Uri]::new($base), $path).ToString()
}

应该很容易扩展到多个部分

Powershell有一个-join运算符。有关帮助,请键入help about_join

最新更新