Share via

Powershell custom objects

Gan Herng Yih 41 Reputation points
2020-11-24T07:11:46.587+00:00

Hi Folks
I was wondering why a PS custom object will not be displayed according to sequence? It will be displayed last no matter what.

`$table= @()
$table += New-Object psobject -Property @{SID ="ola";MG="$MG"}

$table

write-host "lol"`

Output:
Notice that the string "lol" displayed first regardeless

lol
SID MG


ola 2d

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

Answer accepted by question author
  1. Rich Matheisen 48,116 Reputation points
    2020-11-24T16:04:33.967+00:00

    It has nothing to do with PSCustomObject. The statement "$table" is sent to stream 1 (the "Success" stream). Write-Host is sending the output directly to the host. If you want them written in the order you expect, use Write-Output instead of Write-Host.

    understanding-streams-redirection-and-write-host-in-powershell


3 additional answers

Sort by: Most helpful
  1. Anonymous
    2020-11-25T10:06:39.03+00:00

    Hi,

    The object $table is sent to the pipeline that the script is runing and will be piped to Out-Default by default
    https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/out-default?view=powershell-7.1

    0 comments No comments

  2. js2010 191 Reputation points
    2020-11-25T00:07:15.8+00:00

    It's hard to understand your code. But usually objects are implicitly sent through format-table, which has a slight delay so it can see how to align columns.

    0 comments No comments

  3. Bill Stewart 186 Reputation points
    2020-11-24T15:26:11.753+00:00

    This is likely an implementation detail (there's a difference between standard output and host-only output).

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.