![](/img/trans.png)
[英]Why does PowerShell always use US culture when casting to DateTime?
[英]Why does casting PSCustomObjects to custom type with DateTime in PowerShell fails?
我想将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
但是,您可以使用手工制作的函数将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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.