我想将PSCustomObjects转换为自定义类型。强制转换确实适用于简单类型,但是如果我在类型定义中使用例如DateTime,则无法使用。从HashTable强制转换为自定义类型确实可行。为什么从PSCustomObject进行投射无法正常工作?
这是一个例子:
Add-Type @"
using System;
public struct Test {
public DateTime date;
}
"@
$Properties = @{date=(Get-Date)}
$CustomObject = New-Object -TypeName PSCustomObject -Property $Properties
# Returns correct date:
$TestObjectCastFromProperties = [Test]$Properties
$TestObjectCastFromProperties
$TestObjectCastFromProperties.GetType()
# Returns wrong date
$TestObjectCastFromCustomObject = [Test]$CustomObject
$TestObjectCastFromCustomObject
$TestObjectCastFromCustomObject.GetType()
我不能告诉你为什么这行不通。甚至显式转换也会失败:
[System.Management.Automation.LanguagePrimitives]::ConvertPSObjectToType(
$CustomObject, [test], $true, [cultureinfo]::InvariantCulture, $false)
输出:
date
----
01.01.0001 00:00:00
但是,您可以使用手工函数将a转换PSCustomObject
为Type
:
function Cast-CustomObject
{
Param
(
[PsCustomObject]$obj,
[Type]$castType
)
$properties = ($obj.PSObject.Properties | % { @{$_.Name = $_.Value}})
[System.Management.Automation.LanguagePrimitives]::ConvertTo($properties, $castType)
}
用法:
Cast-CustomObject -obj $CustomObject -castType ([Test])
输出:
date
----
06.07.2016 08:52:01
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句