1

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

mortenma71
  • 1,078
  • 2
  • 9
  • 27

1 Answers1

1

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
mortenma71
  • 1,078
  • 2
  • 9
  • 27
  • 4
    Your answer is inefficient. Simply doing `$array.Id -join ','` or `$collection.Name -join ','` would have done the trick. – Santiago Squarzon Jun 05 '21 at 06:19
  • Great. I didn't know this trick. I updated my answer. Thanks – mortenma71 Jun 05 '21 at 06:29
  • 2
    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](https://stackoverflow.com/a/60708579/1701026). In other words build your collection from the pipeline: `$array = $o1, $o2, $o3` – iRon Jun 05 '21 at 07:31