问题
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.
回答1:
You could do something like the following, which keeps closely to your current logic. This does assume that the order of data in your file is exactly as you have stated. .
switch -regex -file people.csv {
'\d' { $Attributes.Add($_) }
default {
if ($Attributes -and $Name) {
[pscustomobject]@{Name = $Name; Attributes = $Attributes}
}
$Name = $_
$Attributes = [Collections.Generic.List[string]]@()
}
}
# Output Last Set of Attributes
[pscustomobject]@{Name = $Name; Attributes = $Attributes}
# Cleanup
Remove-Variable Name
Remove-Variable Attributes
If there are no attributes for a name, that name is ignored. That feature can be changed by adding a condition elseif ($Name) { [pscustomobject]@{Name = $Name; Attributes = $null} }
within the default
block.
来源:https://stackoverflow.com/questions/60248417/how-to-instantiate-an-object-and-set-member-fields-with-powershell