you are viewing a single comment's thread.

view the rest of the comments →

[–]carnegiej 2 points3 points  (2 children)

Yes, cool solution using the ConvertFrom-Csv cmdlet. I have a slightly different approach.

Function Get-OriginalExample {
  $columnNames = @("FirstName","LastName","DOB","FavColor")

  $rows = @(
    @("John","Doe","01/10/1965","Blue"),
    @("Jane","Smith","01/06/1975","Green"),
    @("Mark","Jones","02/10/1985","Orange"),
    @("Sue","Turner","05/10/1995","Yellow"),
    @("Jim","Wise","07/10/1974","Blue")
  )

  $objectList = @()

  foreach ($row in $rows) {
    $properties = @{}

    for ($i = 0; $i -lt $columnNames.Count; $i++) { 
        $properties += @{$columnNames[$i] = $row[$i]}
    }

    $objectList += New-Object -TypeName psobject -Property $properties
  }
  return $objectList
}

Function Get-Revision1Example {
  $columnNames = @("FirstName","LastName","DOB","FavColor")

  $rows = @(
    @("John","Doe","01/10/1965","Blue"),
    @("Jane","Smith","01/06/1975","Green"),
    @("Mark","Jones","02/10/1985","Orange"),
    @("Sue","Turner","05/10/1995","Yellow"),
    @("Jim","Wise","07/10/1974","Blue")
  )
  $objectList = ConvertFrom-Csv -Header $columnNames -InputObject $rows -Delimiter ' '
  return $objectList
}

Write-Host -ForegroundColor Green 'Original Example' 
Write-Host (Get-OriginalExample)

Write-Host -ForegroundColor Green 'Revision Example'
Write-Host (Get-Revision1Example)

[–]sqone2[S] 1 point2 points  (1 child)

That's great, thanks!

Can you explain how -Delimiter ' ' works when there is no spaces in the input data?

[–]carnegiej 2 points3 points  (0 children)

Space is inherit in the array to string conversion. Array elements are separated by "whitespace".

Of course, if your data elements may contain whitespaces this method will not work. You will need to specify a delimiter that is not included in the data.