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 Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,389 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,096 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. Bill Stewart 181 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

  2. js2010 186 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. Ian Xue (Shanghai Wicresoft Co., Ltd.) 30,376 Reputation points Microsoft Vendor
    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