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

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 

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

begin {
    [string] $string = '';
    $first  =  $true;
}

process {
    foreach ( $element in $_ ) {
        #Skip blank elements if -Collapse is specified
        if ( $Collapse -and ($element -eq '' -or $element -eq $null ) ) {
            continue
        }

        if ($first) {
            $string = $_
            $first  = $false
        }
        else {
            $string += $separator + $element -as [string]
        }
    }
}

end {
    $string
}

}

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

Leave a Reply