在Powershell中导出到CSV时如何选择对象类型

时间:2019-09-08 07:15:13

标签: arrays powershell export-to-csv

我的数组$list包含多种对象类型。一个是字符串,一个是字符串 PSCustomObject

当我将其传送到Export-Csv时,我得到的只是第一个字符串对象,该对象将返回无用的结果。

PS C:\data\functions> $list | gm


   TypeName: System.String

Name             MemberType            Definition                                                                           
----             ----------            ----------                                                                           
Clone            Method                System.Object Clone(), System.Object ICloneable.Clone()                              
CompareTo        Method                int CompareTo(System.Object value), int CompareTo(string strB), int IComparable.Co...


--- Output removed ----

   TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition                    
----        ----------   ----------                    
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()             
GetType     Method       type GetType()                
ToString    Method       string ToString()             
Direction   NoteProperty string Direction=both         
Hostname    NoteProperty string Hostname=Desktop1         
Target      NoteProperty string Target=Rental                

PS C:\data\functions> $list| Export-Csv -Path "c:\data\list.txt" -NoTypeInformation

PS C:\data\functions> Get-Content "C:\data\list.txt"
"Length"
"5"

我尝试通过使用将对象强制转换为PSCustomObject [PSCustomObject] $list[PSCustomObject[]] $list。 我已经尝试过$list | out-File -FilePath "c:\data\list.txt"。这确实给了我在终端上显示的数组内容

hello

Hostname  : Desktop1
Target    : Rental

Hostname  : Desktop2
Target    : Rental

Hostname  : Desktop3
Target    : Rental

Hostname  : Desktop4
Target    : Rental

我希望得到一个CSV文件

1 个答案:

答案 0 :(得分:1)

我想说的是,您必须选择所需的属性,否则它不会全部保存。

$a = [pscustomobject]@{name='Joe'}
$b = [pscustomobject]@{address='here'}
$a,$b | select name,address | export-csv all.csv