Cataster
Cataster

Reputation: 3481

How to display pscustomobject in a loop?

I have the following pscutomobject

$output = [PSCustomObject]@{
    '#' = ''
    'Report Path' = ''
    'Schedule ID' = ''
    Status = ''
}

i have a foreach loop and i add values for each iteration into the pscustomobject

foreach ($refreshSchedulePlanId in $reportRefreshScheduleSubscriptionIdDataWithoutHeader)
{
    $output.'#' = $iteration
    $output.'Report Path' = $($reportRefreshScheduleSubscriptionIdDataWithoutHeader[$loopCount])
    $output.'Schedule ID' = $refreshSchedulePlanId
    $output.Status = $status

    $output | ft
}

but its outputting this way:

# Report Path Schedule ID Status
1 report1/rep1 0998989898 success

# Report Path Schedule ID Status
2 report2/re2 76767868767 fail

it should output:

# Report Path Schedule ID Status
1 report1/rep1 0998989898 success
2 report2/re2 76767868767 fail

etc..

Upvotes: 3

Views: 868

Answers (1)

mklement0
mklement0

Reputation: 437062

By using ft (Format-Table) inside your loop, each custom object is formatted instantly, individually, printing as a complete table - complete with header - every time.

The immediate fix is to move the ft call out of the loop and apply it to the whole loop:

& { 
  foreach ($refreshSchedulePlanId in $reportRefreshScheduleSubscriptionIdDataWithoutHeader)
  {
    $output.'#' = $iteration
    $output.'Report Path' = $($reportRefreshScheduleSubscriptionIdDataWithoutHeader[$loopCount])
    $output.'Schedule ID' = $refreshSchedulePlanId
    $output.Status = $status

    $output
  }
} | ft

Note: Since a foreach loop is a statement, it can't be used as-is in a pipeline, and is therefore wrapped in a script block ({ ... }) invoked with &, the call operator.

However, since your [pscustomobject] instances have only 4 properties, you do not need ft (Format-Table at all, because PowerShell by default uses table formatting with custom objects that have 4 or fewer properties.

Not using a Format-* cmdlet has the added advantage that the output remains suitable for further programmatic processing, given that Format-* cmdlets are only ever useful for display formatting, given that the objects they return are formatting instructions to PowerShell's output-formatting system - see this answer.

Upvotes: 5

Related Questions