I would like to cast PSCustomObjects to custom types. Casting does work for simple types, but it doesn't work if I use e.g. DateTime within the type definition. Casting from a HashTable to custom type does work. Why does casting from PSCustomObject does not work as expected?
Here's an example:
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()
I can't tell you why this doesn't work. Even the explicit conversion fails:
[System.Management.Automation.LanguagePrimitives]::ConvertPSObjectToType(
$CustomObject, [test], $true, [cultureinfo]::InvariantCulture, $false)
Output:
date
----
01.01.0001 00:00:00
However, you could use a handcrafted function to convert a PSCustomObject to a Type:
function Cast-CustomObject
{
Param
(
[PsCustomObject]$obj,
[Type]$castType
)
$properties = ($obj.PSObject.Properties | % { @{$_.Name = $_.Value}})
[System.Management.Automation.LanguagePrimitives]::ConvertTo($properties, $castType)
}
Usage:
Cast-CustomObject -obj $CustomObject -castType ([Test])
Output:
date
----
06.07.2016 08:52:01
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With