How to initialize an array of custom objects

后端 未结 9 2438
粉色の甜心
粉色の甜心 2020-12-13 23:44

First, as this leads to my question, I\'ll start by noting that I\'ve worked with XML a fair bit in PowerShell, and like how I can read data from XML files, quickly, into ar

9条回答
  •  無奈伤痛
    2020-12-14 00:24

    Given the data above, this is how I would do it:

    # initialize the array
    [PsObject[]]$people = @()
    
    # populate the array with each object
    $people += [PsObject]@{ Name = "Joe"; Age = 32; Info = "something about him" }
    $people += [PsObject]@{ Name = "Sue"; Age = 29; Info = "something about her" }
    $people += [PsObject]@{ Name = "Cat"; Age = 12; Info = "something else" }
    

    The below code will work even if you only have 1 item after a Where-Object:

    # display all people
    Write-Host "People:"
    foreach($person in $people) {
        Write-Host "  - Name: '$($person.Name)', Age: $($person.Age), Info: '$($person.Info)'"
    }
    
    # display with just 1 person (length will be empty if using 'PSCustomObject', so you have to wrap any results in a '@()' as described by Andrew Savinykh in his updated answer)
    $youngerPeople = $people | Where-Object { $_.Age -lt 20 }
    Write-Host "People younger than 20: $($youngerPeople.Length)"
    foreach($youngerPerson in $youngerPeople) {
        Write-Host "  - Name: '$($youngerPerson.Name)'"
    }
    

    Result:

    People:
      - Name: 'Joe', Age: 32, Info: 'something about him'
      - Name: 'Sue', Age: 29, Info: 'something about her'
      - Name: 'Cat', Age: 12, Info: 'something else'
    People younger than 20: 1
      - Name: 'Cat'
    

提交回复
热议问题