Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell write-output bug with multiple objects in a script? [duplicate]

Tags:

powershell

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.

like image 804
js2010 Avatar asked Oct 18 '22 10:10

js2010


1 Answers

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.

like image 79
Windos Avatar answered Nov 03 '22 05:11

Windos