开发者

Could someone explain this bizarre PSObject + add-member behavior for Powershell?

I just don't understand why this is happening. If I create two separate new PSObjects, they seem to affect each other. For example, with this code:

$o1 = new-object psobject
$o1 | add-member noteproperty abc 123

$o2 = new-object psobject
$o2 | add-member noteproperty def 456

write-output $o1
write-output $o2

I would expect to see output for both abc and def, yet I only get abc:

abc
---
123

If I use write-host instead, like this:

write-host $o1
write-host $o2

Then it shows output like this:

@{abc=123}
@{def=456}

So according to write-output, $o2 is null/empty, but write-host says that's a li开发者_StackOverflow中文版e.

What's going on?


If you run the sample lines from the console, you will see no issue. If you run them all in a script you will see an issue. This is because Out-Default (which is at the end of every pipeline) bases its formatting decisions on the first object it sees. So you need to make sure that you are not output more than one object type. Or if you are, you need to create some formatting rules that handle all the object types (like what is done for directory and file output from Get-ChildItem).


If you output multiple different objects in a script, the columns that are output depend on the first item in the pipeline. Since the first PSObject only had a abc property, the second object didn't output anything since it didn't have a matching property.

P.S. You won't see this behavior if you execute it one line at a time.


I am not able to reproduce the problem you are seeing, but I did notice that the formatted output of write-output shows the object on the far right side of the console. I actually missed it the first time I saw it. If I pipe it to format-list I get the following.

39 >  $o1 = new-object psobject
40 >  $o1 | add-member noteproperty abc 123
41 >  $o2 = new-object psobject
42 >  $o2 | add-member noteproperty def 456
43 >
43 >  write-output $o1 | fl

abc : 123

44 >  write-output $o2 | fl

def : 456
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜