Thufir
Thufir

Reputation: 8487

How to set a custom objects attribute with Powershell?

How do I add String data to the array of the class OnePerson in order to group the data?

$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

output:

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$ 

Upvotes: 0

Views: 58

Answers (1)

Jawad
Jawad

Reputation: 11364

Example on how you can use OnePerson class and adding that element to your array is,

class OnePerson {
  [String] $Info

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

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

Constructors you use in class have to have the same name as your class itself. Once the person has been created and added to myArray, it no longer exists on it's own, only available via reference from myArray

Upvotes: 1

Related Questions