Search code examples
powershellorder-of-executionpscustomobject

Powershell problem with order of execution in script


I'm having a problem with unexpected order of things being run and returned in the below Powershell script.

The Write-ArrayToTable function is to output the data in the arrays in a pretty table-like fashion via custom object.

The problem is when I call my Write-ArrayToTable function, it then does not return the data until AFTER the Read-Host command returns.

Below is the output from a run of the script, and the code itself is below that. The table output should be displayed BEFORE the Read-Host call but is instead held until the end and then displayed.

What am I missing? Any help greatly appreciated!

Output:

Test: y
Label1 Label2
------ ------
Test1  Test3
Test2  Test4
y

Code:

Function Write-ArrayToTable{
  param(
      [String[]]$Names,
      [Object[][]]$Data
  )
  for($i = 0;; ++$i){
    $Props = [ordered]@{}
    for($j = 0; $j -lt $Data.Length; ++$j){
      if($i -lt $Data[$j].Length){
        $Props.Add($Names[$j], $Data[$j][$i])
      }
    }
    if(!$Props.get_Count()){
      break
    }
    [PSCustomObject]$Props
  }
}

$arr1 = @("Test1","Test2")
$arr2 = @("Test3","Test4")

Write-ArrayToTable "Label1","Label2" $arr1,$arr2

Read-Host "Test"

Solution

  • Instead of dropping you objects like this:

    [PSCustomObject]$Props
    

    You can be more explicit:

    $Props | Out-String
    

    If you want to print all objects in one table, collect them first, before printing:

    Function Write-ArrayToTable{
      param(
          [String[]]$Names,
          [Object[][]]$Data
      )
      $myProps = for($i = 0;; ++$i){
        $Props = [ordered]@{}
        for($j = 0; $j -lt $Data.Length; ++$j){
          if($i -lt $Data[$j].Length){
            $Props.Add($Names[$j], $Data[$j][$i])
          }
        }
        if(!$Props.get_Count()){
          break
        }
        [PSCustomObject]$Props
      }
      $myProps | Format-Table
    }