【发布时间】:2020-02-24 13:23:11
【问题描述】:
我遇到了一些问题,无法弄清楚问题所在。我有一个生成 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 过滤了对象。我去掉了select对象,成员类型不变。
TypeName: System.Management.Automation.PSCustomObject
【问题讨论】:
-
它“打印正确”但“格式不适用” - 听起来像是矛盾的陈述 - 你能显示你得到的输出与你期望的输出吗?
$GAMOBJ |Get-Member的输出在这里也可能有用 -
它打印正确,因为对象是从 CSV 输出创建的,但对象类型没有改变,所以我的自定义表不适用。
-
这是 Get-Member TypeName 的输出:Selected.System.Management.Automation.PSCustomObject
-
修改类型名称不会改变类型,但会影响格式化系统。 (请edit your original post 输出
Get-Member并打印输出)。此外,请仔细检查System.Gam.Device的任何自定义格式数据是否实际存在于Get-FormatData -TypeName 'System.Gam.Device' -
完成。我已经使用 $var.PSObject.TypeName.Insert(0, 'TypeName') 来更改我创建的 PSCustomObject 的类型名,它工作得很好,但我无法得到这个。不会产生错误,只是不会更改类型名称。
标签: powershell csv