5

Is this a powershell bug? It will only print $var1, not $var2 inside a script (I can't pipe it to where-object either). But when I copy and paste it to the command line it works fine.

$var1 = New-Object -TypeName PSObject -Prop @{'data1'=6}
write-output $var1
$var2 = New-Object -TypeName PSObject -Prop @{'data2'=12}
write-output $var2


data1
------
6

EDIT: I think I'm starting to get it. Here's a weirder example. You can only output or process common fields from the second object:

$var1 = New-Object PSObject -prop @{data1=6;data3=5}
$var1
$var2 = New-Object PSObject -prop @{data2=12;data3=6}
$var2


data1 data3
----- -----
    6     5
          6

EDIT2: this has to do with the implied running of format-table, and how it sets up columns.

js2010
  • 23,033
  • 6
  • 64
  • 66

1 Answers1

3

I think this is the expected behavior of the Write-Output cmdlet. It's sending objects down the pipeline (and if it's the last cmdlet in the pipeline it's display to the host.) It's expecting that all of the objects coming down the pipeline have the same properties.

In your example, you have one object with the property data1 and a second object with data2. If you make both of your objects use the same property, it'll work as you expect:

$var1 = New-Object -TypeName PSObject -Prop @{'data1'=6}
write-output $var1
$var2 = New-Object -TypeName PSObject -Prop @{'data1'=12}
write-output $var2

data1
-----
    6
   12

Think of it like this, cmdlets normally output a single, predictable, object (Get-AdUser outputs AdUser objects.) The pipeline and other cmdlets wouldn't be able to handle it if Get-AdUser output a smattering of AdUser, AdGroup, Mailbox, and NTFSPermissions as one data stream.

Edit: As an aside, if you're just looking at getting information on the screen without using Write-Host, consider Write-Information.

Windos
  • 1,796
  • 1
  • 13
  • 19
  • 1
    "...When it [Out-Default] sends the stream to Format-Table, that command needs to generate columns. It does this by looking at the properties of the FIRST OBJECT – those become the columns. If the first Object has 2 properties, you'll get a 2 column table even if all the other objects in the stream have 10 properties." -- https://blogs.msdn.microsoft.com/powershell/2006/04/29/how-powershell-formatting-and-outputting-really-works/ – js2010 Jun 19 '17 at 17:19