regex - 如何使用 PowerShell 实例化对象并设置成员字段?
问题描述
我正在尝试研究如何创建对象、为该对象设置字段,然后将该对象添加到集合中。
具体来说,如何创建一个字段为“joe”且由“phone1、phone2、phone3”组成$newPerson
的字段?类似地,“sue”有一个数组“cell4 etc”和“alice”及其属性,等等。最终,要将这三个对象放入一个对象数组中,?Name
array
$collectionOfPeople
输出:
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$
代码:
$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???
从CSV
文件输入:
people
joe
phone1
phone2
phone3
sue
cell4
home5
alice
atrib6
x7
y9
z10
在上面CSV
的记录之间没有标记,所以我使用一个if
声明,假设每个属性都有数字,而名称从来没有数字。
解决方案
您可以执行以下操作,这与您当前的逻辑密切相关。这确实假设您文件中的数据顺序与您所说的完全相同。.
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
如果名称没有属性,则忽略该名称。elseif ($Name) { [pscustomobject]@{Name = $Name; Attributes = $null} }
可以通过在default
块中添加条件来更改该功能。