将 Powershell 对象的类型名称从 PSCustomObject 更改为我选择的名称? [英] Change the type name of a Powershell object from PSCustomObject to something I choose?

查看:37
本文介绍了将 Powershell 对象的类型名称从 PSCustomObject 更改为我选择的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用自定义对象的脚本.我用这样的伪构造函数创建它们:

I have a script that uses custom objects. I create them with a pseudo-constructor like this:

function New-TestResult 
{
    $trProps = @{
        name = "";
        repo = @{};

        vcs   = $Skipped;

        clean = New-StageResult; # This is another pseudo-constructor
        build = New-StageResult; # for another custom object.
        test  = New-StageResult; #     - Micah

        start = get-date;
        finish = get-date;
    }

    $testResult = New-Object PSObject -Property $trProps
    return $testResult
}

这些很有用,因为它们可以传递给诸如 ConvertTo-CsvConvertTo-Html 之类的东西(不像哈希表,否则会实现我的目标).它们被输入为 PSCustomObject 对象.这段代码:

These are useful because they can be passed to something like ConvertTo-Csv or ConvertTo-Html (unlike, say, a hashtable, which would otherwise accomplish my goals). They are typed as PSCustomObject objects. This code:

$tr = new-testresult
$tr.gettype()

返回:

IsPublic IsSerial Name                     BaseType
-------- -------- ----                     --------
True     False    PSCustomObject           System.Object

我可以将返回的 Name 字段从 PSCustomObject 更改为其他内容吗?

Can I change the Name field returned there from PSCustomObject to something else?

稍后当我整理测试结果时,我将传递给另一个函数,有时是单个结果,有时是结果数组.我需要能够做一些不同的事情,这取决于我得到的那些.

Later on when I'm collating test results, I'll pass to another function what will sometimes be an individual result, and sometimes an array of results. I need to be able to do something different depending on which of those I get.

感谢任何帮助.

推荐答案

好的,在创建 $testResult 后试试这个:

Sure, try this after creating $testResult:

$testResult.psobject.TypeNames.Insert(0, "MyType")

PowerShell 扩展类型系统的核心是 psobject 包装器(至少在 V1 和 V2 中).此包装器允许您添加属性和方法、修改类型名称列表并获取底层 .NET 对象,例如:

The heart of the PowerShell extended type system is the psobject wrapper (at least in V1 and V2). This wrapper allows you to add properties and methods, modify type names list and get at the underlying .NET object e.g.:

C:\PS > $obj = new-object psobject
C:\PS > $obj.psobject


BaseObject          :
Members             : {string ToString(), bool Equals(System.Object obj), int GetHashCode(), type GetType()}
Properties          : {}
Methods             : {string ToString(), bool Equals(System.Object obj), int GetHashCode(), type GetType()}
ImmediateBaseObject :
TypeNames           : {System.Management.Automation.PSCustomObject, System.Object}

或者从提示中尝试:

C:\PS> $d = [DateTime]::Now
C:\PS> $d.psobject
...

这篇关于将 Powershell 对象的类型名称从 PSCustomObject 更改为我选择的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆