0

TL;DR: I'm trying to build an array with headers based off a condition, ideally looking like this.

Name        Value        Status
Element 1   Value 1      --
Element 2   Value 2      Action Required
Element 3   Value 3      --

I've been trying it different ways but here are my two latest attempts:

This outputs the last line of every row (as the $array += $list is within the if..else statement). However when it is outside the if..else it comes up with a null value. Appending the $list to the $array does not seem to be working for me (I'm doing something wrong).

$array = @()
$list = "" | Select Name,Value,Status
foreach ($row in $worksheet) {
  $row.Psobject.Properties | ? {
    if ($RuleArray -contains $_.Name) {
      $list.Name = $_.Name; 
      $list.Value = $_.Value; 
      $list.Status = "Action Required" 
      $array += $list
    } else {
      $list.Name = $_.Name; 
      $list.Value = $_.Value; 
      $list.Status = "--" 
      $array += $list
    }
  } 
}
Write-Host $array

The next attempt uses a string to store the values but I have not managed to place a header on the string, and the formatting as a result is non existent. The upside is that I at least see the values I am expecting, so I know the condition works.

$array = @()
$list = New-Object System.Collections.Generic.List[System.String]
foreach ($row in $worksheet) {
  $d = $row.Psobject.Properties | % {
    if ($RuleArray -contains $_.Name) {
      $_.Name; $_.Value; "Action Required`n"
    } else {
      $_.Name; $_.Value; "--`n"
    }
  }
  $list.Add($d)
}
$array = "" | Select Name,Value,Status #hail mary
$array += $list.ToArray()
Write-Host $array 

Any idea on where I'm going wrong?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
M O'Connell
  • 487
  • 5
  • 18

1 Answers1

0

The usual approach is to create a list of custom objects with a defined set of properties, like this:

foreach ($row in $worksheet) {
  $row.Psobject.Properties | ForEach-Object {
    New-Object -Type PSObject -Property @{
      Name   = $_.Name
      Value  = $_.Value
      Status = if ($RuleArray -contains $_.Name) {'Action Required'} else {'--'}
    }
  }
}

or like this:

foreach ($row in $worksheet) {
  $row.Psobject.Properties |
    Select-Object Name, Value, @{n='Status';e={
      if ($RuleArray -contains $_.Name) {'Action Required'} else {'--'}
    }}
}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • Thank you very much! I'm wrapping my head around custom objects but clearly have a lot to learn. Thanks again @AnsgarWiechers, fantastic solution. – M O'Connell Feb 02 '16 at 21:53