首页 > 解决方案 > 更改 ConvertFrom-CSV 对象的类型

问题描述

我被困在某事上,我无法弄清楚问题是什么。我有一个生成 CSV 格式文本以供输出的命令。我已使用 ConvertFrom-CSV 成功地将 CSV 输出转换为 Powershell 对象。一切都很好!我想应用一些自定义格式,所以我想将对象转换为自定义 pstype 名称。我不能让它改变类型。ConvertFrom-CSV 输出一个 PSCustomObject,所以我认为这很容易,但到目前为止还没有运气。

我的代码:

##This would be a function "get-devices" that creates command text and outputs the CSV output
##This all works properly
function get-devices {
     $Command.Invoke() | ConvertFrom-Csv
}
$GAMOBJ = get-devices
$GAMOBJ.PSObject.TypeNames.Insert(0,"System.Gam.Device")
$GAMOBJ

该对象可以正确打印,但仍为PSCustomObject,因此格式不适用。我错过了什么?

任何帮助表示赞赏,在此先感谢。

这是 Get-Member 的输出:

       TypeName: Selected.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()                            
    AssetID     NoteProperty System.String AssetID=ASSETID            
    Expiration  NoteProperty System.String Expiration=2000-01-01          
    Location    NoteProperty System.String Location=LOCATION          
    Model       NoteProperty System.String Model=CHROMEBOOKMODEL
    OU          NoteProperty System.String OU=/                           
    Serial      NoteProperty System.String Serial=123456                 
    Status      NoteProperty System.String Status=ACTIVE

有人在下面补充说我已经使用 Select-Object 过滤了对象。我删除了选择对象,成员类型不变。

    TypeName: System.Management.Automation.PSCustomObject

标签: powershellcsv

解决方案


您必须将您的 ETS 类型名称插入每个对象的 .PSTypeNames集合(又名.psobject.TypeNames)中:

$GAMOBJ.ForEach({ $_.PSTypeNames.Insert(0, "System.Gam.Device") })

否则,您只是将类型名称作为一个整体应用于数组,这与逐个打印对象无关。


推荐阅读