I need to join multple Url elements into one string, so I wrote the generic Join-Parts function:
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
Which returns as expected:
http://mysite/sub/subsub/one/two/three
http://mysite/one/two/three
http://mysite/one/two/three
http://mysite/one/two/three
1234
I have the feeling that this is not the smartest approach. Any ideas on a better approach?
UPDATE
Based on the answer by @sorens I changed the function into:
function Join-Parts
{
param
(
$Parts = $null,
$Separator = ''
)
($Parts | ? { $_ } | % { ([string]$_).trim($Separator) } | ? { $_ } ) -join $Separator
}