Skip to content

Instantly share code, notes, and snippets.

@gabriel-vanca
Last active August 15, 2024 22:49
Show Gist options
  • Save gabriel-vanca/b7195e0a05e592c0e249d326406a5809 to your computer and use it in GitHub Desktop.
Save gabriel-vanca/b7195e0a05e592c0e249d326406a5809 to your computer and use it in GitHub Desktop.
Join-Strings
function Join-Strings
{
<#
.SYNOPSIS
Join strings with a specified separator.
.DESCRIPTION
Join strings with a specified separator.
This strips out null values and any duplicate separator characters.
See examples for clarification.
.PARAMETER Separator
Separator to join with
.PARAMETER Parts
Strings to join
.EXAMPLE
Join-Strings -Separator "/" this //should $Null /work/ /well
# Output: this/should/work/well
.EXAMPLE
Join-Strings -Parts http://this.com, should, /work/, /wel
# Output: http://this.com/should/work/wel
.EXAMPLE
Join-Strings -Separator "?" this ?should work ???well
# Output: this?should?work?well
.EXAMPLE
$CouldBeOneOrMore = @( "JustOne" )
Join-Strings -Separator ? -Parts $CouldBeOneOrMore
# Output JustOne
# If you have an arbitrary count of parts coming in,
# Unnecessary separators will not be added
.NOTES
Credit to Rob C. and Michael S. from this post:
https://stackoverflow.com/questions/9593535/best-way-to-join-parts-with-a-separator-in-powershell
#>
[CmdletBinding()]
[OutputType([String])]
param
(
[Parameter (Mandatory = $False)]
[string]$Separator = "/",
[Parameter(
Mandatory = $False,
ValueFromRemainingArguments=$true)]
[ValidateNotNullOrEmpty()]
[string[]]$Parts = $null
)
return (( $Parts |
Where-Object { $_ } |
ForEach-Object { ( [string]$_ ).trim($Separator) } |
Where-Object { $_ }
) -join $Separator)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment