如何使用Powershell设置自定义对象属性?

问题描述 投票:0回答:1

如何将String数据添加到array类的OnePerson以便group数据?

$people = import-csv "./people.csv"


class OnePerson {
  [String] $Info

  people () { } 
}

$myPerson = New-Object -TypeName OnePerson

$manyPeople = New-Object System.Object

$myArray = @()

ForEach ($person in $people) {

  if ($person -match '[0-9]') {
    Write-host $person
    #add $person string to the array $Info of $myPerson
  }
  else { 
    write-host "new person"
    write-host $person
    $myArray += $myPerson
    $myPerson = New-Object -TypeName OnePerson
  }
}

write-host $myArray

输出:

thufir@dur:~/flwor/people$ 
thufir@dur:~/flwor/people$ pwsh foo.ps1 
new person
@{people=joe}
@{people=phone1}
@{people=phone2}
@{people=phone3}
new person
@{people=sue}
@{people=cell4}
@{people=home5}
new person
@{people=alice}
@{people=atrib6}
@{people=x7}
@{people=y9}
@{people=z10}
OnePerson OnePerson OnePerson
thufir@dur:~/flwor/people$ 
powershell oop object syntax instantiation
1个回答
1
投票

有关如何使用OnePerson类并将该元素添加到数组的示例,

class OnePerson {
  [String] $Info

  OnePerson () { } 
  OnePerson ([String]$newinfo) { $this.Info = $newInfo }
}

$myArray = @()
$myArray += [OnePerson]::new("John")
$myArray += [OnePerson]::new("Smith")

您在课堂上使用的构造函数必须与课程本身具有相同的名称。创建人员并将其添加到myArray后,它就不再存在,只能通过myArray的引用来使用

© www.soinside.com 2019 - 2024. All rights reserved.