I'm trying to work out how to create objects, set fields for that object, and then add the object to a collection.
Specifically, how can I create a $newPerson
where the Name
field is "joe" and with an array
consisting of "phone1, phone2, phone3"? Similarly, "sue" has an array of "cell4 etc" and "alice" with her attributes, and so on. Ultimately, to put these three objects into an array of objects, $collectionOfPeople
?
output:
thufir@dur:~/flwor/csv$
thufir@dur:~/flwor/csv$ pwsh import.ps1
people name
joe name
phone1 attribute
phone2 attribute
phone3 attribute
sue name
cell4 attribute
home5 attribute
alice name
atrib6 attribute
x7 attribute
y9 attribute
z10 attribute
thufir@dur:~/flwor/csv$
code:
$tempAttributes = @()
$collectionOfPeople = @()
function attribute([string]$line) {
Write-Host $line "attribute"
$tempAttributes += $line
}
function name([string]$line) {
Write-Host $line "name"
#is a $newPerson ever instantiated?
$newPerson = [PSCustomObject]@{
Name = $line
Attributes = $tempAttributes
}
$newPerson #empty? no output
$collectionOfPeople += $newPerson
$tempAttributes = @()
}
$output = switch -regex -file people.csv {
'\d' { attribute($_) ; $_ }
default { name($_); $_ }
}
#how to read the file from top to bottom?
#[array]::Reverse($output)
#$output
$collectionOfPeople #empty???
input from a CSV
file:
people
joe
phone1
phone2
phone3
sue
cell4
home5
alice
atrib6
x7
y9
z10
In the above CSV
there's no marker between records, so I'm using an if
statement on the assumption that every attribute has digits while the names never have digits.