Last active
August 15, 2024 22:49
-
-
Save gabriel-vanca/b7195e0a05e592c0e249d326406a5809 to your computer and use it in GitHub Desktop.
Join-Strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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