我有一个使用自定义对象的脚本.我用这样的伪构造函数创建它们:
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
}
Run Code Online (Sandbox Code Playgroud)
这些都是有用的,因为它们可以被传递到类似ConvertTo-Csv或ConvertTo-Html(不像,说,一个哈希表,否则将完成我的目标).它们被输入为PSCustomObject对象.这段代码:
$tr = new-testresult
$tr.gettype()
Run Code Online (Sandbox Code Playgroud)
返回:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False PSCustomObject System.Object
Run Code Online (Sandbox Code Playgroud)
我可以将Name返回的字段更改为其他字段PSCustomObject吗?
稍后当我整理测试结果时,我将传递给另一个函数,有时候会是个别结果,有时候会产生一系列结果.我需要能够根据我得到的不同而做一些不同的事情.
任何帮助表示赞赏.
Kei*_*ill 10
当然,在创建$ testResult之后尝试这个:
$testResult.psobject.TypeNames.Insert(0, "MyType")
Run Code Online (Sandbox Code Playgroud)
PowerShell扩展类型系统的核心是psobject包装器(至少在V1和V2中).这个包装器允许你添加属性和方法,修改类型名称列表并获取底层的.NET对象,例如:
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}
Run Code Online (Sandbox Code Playgroud)
或者从提示中尝试这个:
C:\PS> $d = [DateTime]::Now
C:\PS> $d.psobject
...
Run Code Online (Sandbox Code Playgroud)