Formatting issues / missing data when multiple commands use Select-Object within a script

混江龙づ霸主 提交于 2019-11-29 13:03:28
Matt

The link from mjolinor explains it in more detail but PowerShell is trying to group your outputs together here. An important line from the post states:

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.

In the following example

Get-WmiObject win32_share | select name
Get-WmiObject win32_share | select name, path

When the seconds command has run the output from the previous did not have that property so PowerShell, more specifically Out-Default drops it in output in order to make all the output synchronous.

I would be more curious what your real code was that was creating this issue. Like expirat001 shows you can convert the output to string and this won't happen since they are no longer objects. Be careful doing so as you can lose the original objects this way. Either way the data is not lost. Just not being displayed the way you expect.

Referring back to the example from before we can pretend the first line didn't have a path property. Calling it from select anyway would just create the null column but would allow the other output to be displayed.

# In this next command "path" is not a valid property but PowerShell will create the column anyway
Get-WmiObject win32_share | select name, path 
Get-WmiObject win32_share | select name, path

This is cheating but you could sent one of the commands to a different output stream.

Get-WmiObject win32_share | select name
Get-WmiObject win32_share | select name, path | Out-Host
Get-WmiObject win32_share | select name | ft
Get-WmiObject win32_share | select name, path | ft


Get-WmiObject win32_share | ft name
Get-WmiObject win32_share | ft name, path

The link from mjolinor indeed explains a lot, the main issue here is that you are launching a script via & ./test2.ps1 and the output of this command is piped into Out-Default. In turn, Out-Default sees a set of PSObjects generated by Select-Object cmdlets, and examining the first object (this is the first object returned by Get-WmiObject win32_share | select name) it sees that it has only one property "name" and subsequently formats a table out of resultant objects gathering only name property out of all of them.

To circumvent, use ft or Format-Table cmdlet to turn the output of each line into a sequence of Strings and not PSObjects, this way when the script's output will be piped into Out-Default, it will pass strings through unprocessed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!