1

How do I convert a collection or array of objects into a comma-separated string with just one of the object properties?

1 Answer 1

2

Following the comment from Santiago Squarzon I changed my code to this:

$array.Id -join ','
$collection.Name -join ','

I originally did this:

Objects

$o1 = [PSCustomObject]@{ Name = "John"; Id = 1 }
$o2 = [PSCustomObject]@{ Name = "Jack"; Id = 2 }
$o3 = [PSCustomObject]@{ Name = "Jane"; Id = 3 }

Array

$array = @()
$array = $array + $o1
$array = $array + $o2
$array = $array + $o3

String of Ids

$commaSeparatedStringOfIds = ($array | Select-Object -Property Id | ForEach-Object { $_.Id }) -join ','
$commaSeparatedStringOfIds

Generic.List

$collection = New-Object Collections.Generic.List[System.Object]
$collection.Add($o1)
$collection.Add($o2)
$collection.Add($o3)

String of Names

$commaSeparatedStringOfNames = ($collection | Select-Object -Property Name | ForEach-Object { $_.Name }) -join ','
$commaSeparatedStringOfNames
Sign up to request clarification or add additional context in comments.

3 Comments

Your answer is inefficient. Simply doing $array.Id -join ',' or $collection.Name -join ',' would have done the trick.
Great. I didn't know this trick. I updated my answer. Thanks
Also, the syntax $array = $array + $o1 is quiet inefficient because the $array is mutual, see: Why should I avoid using the increase assignment operator (+=) to create a collection. In other words build your collection from the pipeline: $array = $o1, $o2, $o3

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.