Powershell Join-String function

Update: better yet, read about the -Join and -Split PowerShell operators. Live and learn.
—Geoff

Something I’ve found myself missing in PowerShell is a function to combing the elements of a list with a given separator, like Perl’s join() function. I finally got annoyed enought to write one. It seems to do what I want, so I’m going to add it to my profile.

Here it is in action:

PS C:\> $array = 3.14,'Puppy',$false,'','Green',$null,'foo'
PS C:\> $array | Join-String
3.14,Puppy,False,,Green,,foo
PS C:\> $array | Join-String -collapse
3.14,Puppy,Green,foo
PS C:\> $array | Join-String -collapse ' - '
3.14 - Puppy - Green - foo

Update: Now supports list items as parameter (non-pipeline) usage:

PS C:\> $y = Join-String $array -collapse
PS C:\> $y
3.14,Puppy,False,Green,foo
PS C:\> $y.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

Here’s the code:

# Join-String - A simple pipeline-oriented function to
# concatenate a bunch of strings together with a separator
# Geoffrey.Duke@uvm.edu  Wed 11/17/2010
#   updated 11 July 2013 to handle non-pipeline usage

function Join-String
(   
    [string[]] $list,
    [string] $separator = ',',
    [switch] $Collapse
)
{ 

[string] $string = ''
$first  =  $true

# if called with a list parameter, rather than in a pipeline...
if ( $list.count -ne 0 ) {
    $input = $list
}

foreach ( $element in $input  ) {
    #Skip blank elements if -Collapse is specified
    if ( $Collapse -and [string]::IsNullOrEmpty( $element)  ) {
        continue
    }

    if ($first) {
        $string = $element
        $first  = $false
    }
    else {
        $string += $separator + $element 
    }
}
 
    write-output $string
}

If you have a notion for how it could be improved, please comment.

Leave a Reply