问题描述
使用简单的:
$data = @{
First = 'Justin';
Last = 'Dearing';
StartDate = Get-Date '2002-03-23';
}
关键的StartDate似乎包含一个。
The key StartDate seems to contain a DateTime.
C:\Users\zippy\Documents> $data.StartDate.GetType().FullName
System.DateTime
但是,如果我尝试对其执行二进制序列化,我得到一个异常,抱怨是不可序列化的。
However, if I attempt to perform binary serialization on it, I get an exception complaining that PSObject is not serializable.
$ms = New-Object System.IO.MemoryStream
$bf = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
$bf.Serialize($ms, $data)
$ms.Close()
抛出:
DocumentsException calling "Serialize" with "2" argument(s): "Type 'System.Management.Automation.PSObject' in Assembly 'System.Management.Automation, Versio
n=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable."
At C:\Users\jdearing\AppData\Local\Temp\b8967f99-0a24-41f7-9c97-dad2bc288bd9.ps1:12 char:14
+ $bf.Serialize <<<< ($ms, $data)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
如果我使用显式转换为[DateTime],则此消息将消失,并且一切正常:
This message goes away and everything works if I use an explicit cast to [DateTime] like so:
$data = @{
First = 'Justin';
Last = 'Dearing';
StartDate = [DateTime] (Get-Date '2002-03-23');
}
所以Get-Date不是真的返回一个DateTime,还是其他一些powerhell
So is Get-Date not really returning a DateTime, or is some other powershell oddity at work here.
推荐答案
在PowerShell中的每个对象实际上都是在psobject中透明地包装。我绝大多数透明地说,因为在PowerShell中有几个错误,在将对象泄漏给另一个API之前,省略了删除包装器。这会导致各种各样的问题,就像你现在看到的一样。搜索connect.microsoft.com/powershell的psobject包装器。我相信这不再是v3中使用新的基于DLR的引擎的问题。
Every object in powershell is actually wrapped mostly transparently in a psobject. I say mostly transparently because there are more than a few bugs in powershell that omit to remove the wrapper before leaking the object to another API. This causes all sorts of issues, much like the one you see now. Search connect.microsoft.com/powershell for psobject wrapper. I believe this is no longer an issue in v3 with the new DLR based engine.
这篇关于为什么Get-Date似乎返回DateTime对象,但是BinarySerializer指示它返回一个PSObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!