Repository navigation
Description
There was a PowerShell Team blog post years ago about how serialization works and how it should be possible to customize -- and of course, now I have access to all the source code, but so far I haven't been able to make extending the serialization work. If someone can help me figure this out, I'll make sure we get a HowTo document for future module authors out of it ...
I'm going to use a simple example, but remember that I'm looking for the way to make Deserialization work properly -- I don't want to hear about all the workarounds for this particular case (there are several). The real problem I'm trying to solve is more complicated.
I need to call a remote function which takes a DateTimeOffset object, Unlike DateTime, DateTimeOffest isn't treated as a primitive type (although it should be #3172), so I want to fix that in my module.
Here's what I tried:
using namespace System.Management.Automation
class DateTimeOffsetDeserializer : System.Management.Automation.PSTypeConverter {
[bool] CanConvertFrom([object]$sourceValue, [Type]$destinationType)
{
Write-Warning "CanConvertFrom $SourceValue to $($destinationType.FullName)"
return ([PSObject]$sourceValue).PSTypeNames.Contains("Deserialized.System.DateTimeOffset")
}
[object] ConvertFrom([object]$sourceValue, [Type]$destinationType, [IFormatProvider]$formatProvider, [bool]$ignoreCase)
{
Write-Warning "ConvertFrom $SourceValue to $($destinationType.FullName)"
[PSObject]$psSourceValue = $sourceValue
return [DateTimeOffset]::new($psSourceValue.Ticks, $psSourceValue.Offset)
}
[bool] CanConvertTo([object]$sourceValue, [Type]$destinationType)
{
Write-Warning "CanConvertTo $SourceValue to $($destinationType.FullName)"
return ([PSObject]$sourceValue).PSTypeNames.Contains("Deserialized.System.DateTimeOffset") -and $destinationType -eq "System.DateTimeOffset"
}
[object] ConvertTo([object]$sourceValue, [Type]$destinationType, [IFormatProvider]$formatProvider, [bool]$ignoreCase)
{
Write-Warning "ConvertTo $SourceValue to $($destinationType.FullName)"
[PSObject]$psSourceValue = $sourceValue
return [DateTimeOffset]::new($psSourceValue.Ticks, $psSourceValue.Offset)
}
}
# This should be enough, right?
Update-TypeData -TypeName 'DateTimeOffset' -TargetTypeForDeserialization 'DateTimeOffsetDeserializer' -Force
# I tried adding all the rest of these
Update-TypeData -TypeName 'Deserialized.System.DateTimeOffset' -TargetTypeForDeserialization 'DateTimeOffsetDeserializer' -Force
Update-TypeData -TypeName 'DateTimeOffset' -MemberName 'TargetTypeForDeserialization' -MemberType 'NoteProperty' -Value 'DateTimeOffsetDeserializer'
Update-TypeData -TypeName 'Deserialized.System.DateTimeOffset' -MemberName 'TargetTypeForDeserialization' -MemberType 'NoteProperty' -Value 'DateTimeOffsetDeserializer'But nothing makes the this come out as a DateTimeOffset
using namespace System.Management.Automation
[PSSerializer]::Deserialize( [PSSerializer]::Serialize([DateTimeOffset]::Now) ).PSTypeNamesOr make this not be "Deserialized"
Invoke-Command -ComputerName localhost { [DateTimeOffset]::Now } | % PSTypeNamesOr make this run without crashing:
Invoke-Command -ComputerName localhost { param([DateTimeOffset]$Time) $Time.LocalDateTime } -Args ([DateTimeOffset]::Now)I also tried creating the DateTimeOffsetDeserializer class in C#, but I think I'm misunderstanding that original blog post or something about how the registration works...
Activity
Jaykul commentedon Feb 22, 2017
Ok, after three days of trying ... I finally thought of searching through all of GitHub for use of
TargetTypeForDeserializationand came across the solution. The TypeData needs to be like this:Register the TargetType for the Deserialized type:
Then register the TypeConverter for that TargetType:
This is the part that was completely skipped over in the blog post -- if anyone can add a couple of lines to that post, that would be great! 😉
You can, of course, do all of this in a Types.ps1xml instead:
I should note (because I haven't tested this on PowerShell 3 or 4): the explanation in the SDK makes this somewhat more convoluted -- rather than specifying the actual target type as the
TargetTypeForDeserialization, they state that you should specify the Deserializer as theTargetTypeForDeserialization(i.e. in place ofSystem.DateTimeOffsetabove), which means that you need an extra call (or<Type>entry) to set theSerializationDepth....That makes no sense to me, but perhaps it's actually necessary for some situations or older versions of PowerShell.
iSazonov commentedon Feb 22, 2017
Joel Bennett (@Jaykul) Great gem! Thanks!
You could put this in https://github.com/PowerShell/PowerShell-Docs
Jaykul commentedon Feb 22, 2017
It turns out, there's a different problem: this does not work for PowerShell classes.
Take this simple case for example:
Because it has a custom constructor, you need a custom converter.
To hide some of the sillyness of this, I like to use an intermediate PSObjectConverter:
Finally, register the serialization:
Now, test it. Locally, it works fine:
But when I try to run the command remotely, it just hangs?
Jason Shirk (@lzybkr) Is this just not possible?
lzybkr commentedon Feb 23, 2017
Thanks for the excellent repro.
Getting this scenario to work might be tricky.
Scriptblocks have runspace affinity. Class methods are really just scriptblocks, they get runspace affinity too. I think this is an architectural flaw, but it's not easy to fix without requiring locks throughout the engine.
In this repro - there is only 1 local runspace. The deserialization is happening on a thread with no runspace and it's waiting for the
Invoke-Commandrunspace (the only local runspace, the runspace where the module was imported) to become available to run commands.One fix would be to not block in Invoke-Command - instead timeout and poll for events.
Jaykul commentedon Feb 23, 2017
Thanks. I'll just ... write those classes in C# I guess. But I guess we need to document that you can write C# classes and PowerShell converters but not both in PowerShell, and not PowerShell classes with C# converters (I guess).
Brain2000 commentedon Dec 20, 2018
This is certainly not complete, but will at least let you copy over the class definition and properties to a PSSession. Maybe someone can add methods/constructors...
SSvilen commentedon Jun 10, 2019
Hi Paul Higinbotham (@PaulHigin) - we were discussing the topic of object's rehydration after your session about remoting at PSConfEu. You suggested me to open an issue, so that you can discuss that internally and may be do a blog post about it. It seems that this is not a new topic - so I'll use that issue here as reminder. Thanks to Joel Bennett (@Jaykul) I have something to work with, but may be new blog post about this topic would be a good start
PaulHigin commentedon Jun 18, 2019
Svilen (@SSvilen) Thanks, I am back in office now. I am glad that this helps, but as we discussed this is really something that should be addressed in a blog. I'll try to do so in the not too distant future.
kenny1983 commentedon Oct 20, 2019
Hi guys, just wondering whether there's been any new developments on this issue in the past 4 months, as I'm trying to get the following script working:
Which throws the following error:
Would absolutely adore some guidance on how to get this to work, if it's at all possible. In the meantime, I guess I'll have to go back to using scripts 🙁 MTIA!
Kagre commentedon Mar 10, 2021
I'm not sure if it's related or not, but there also appears to be a scoping issue with
-TargetTypeForDeserialization.{ #<--- Write-Warning's do not show when run inside this scope, & likewise class Test { [string]$FirstName [string]$LastName [string]$FullName Test([string]$FirstName, [string]$LastName) { $this.FirstName = $FirstName $this.LastName = $LastName $this.FullName = $FirstName + " " + $LastName } } # Minifiy: A do-nothing converter, just to hide the "object" methods class PSObjectConverter : System.Management.Automation.PSTypeConverter{ [bool] CanConvertFrom([PSObject]$psSourceValue, [Type]$destinationType){ return $false} [object] ConvertFrom([PSObject]$psSourceValue, [Type]$destinationType, [IFormatProvider]$formatProvider, [bool]$ignoreCase){ throw [NotImplementedException]::new()} # These things down here are just never used. Why they must be here, I have no idea. [bool] CanConvertFrom([object]$sourceValue, [Type]$destinationType){ return $false;} [object] ConvertFrom([object]$sourceValue, [Type]$destinationType, [IFormatProvider]$formatProvider, [bool]$ignoreCase){ throw [NotImplementedException]::new();} [bool] CanConvertTo([object]$sourceValue, [Type]$destinationType){ throw [NotImplementedException]::new();} [object] ConvertTo([object]$sourceValue, [Type]$destinationType, [IFormatProvider]$formatProvider, [bool]$ignoreCase){ throw [NotImplementedException]::new();} } class TestConverter : PSObjectConverter { [bool] CanConvertFrom([PSObject]$psSourceValue, [Type]$destinationType) { Write-Warning "CanConvertFrom $($psSourceValue.PSTypeNames)" return $psSourceValue.PSTypeNames.Contains("Deserialized.Test") } [object] ConvertFrom([PSObject]$psSourceValue, [Type]$destinationType, [IFormatProvider]$formatProvider, [bool]$ignoreCase) { Write-Warning "ConvertFrom $($psSourceValue.PSTypeNames)" Write-Warning "So there can be no doubt this does not work:" Write-Warning ("[Test]::new('" + $psSourceValue.FirstName + "', '" + $psSourceValue.LastName + "')") $Converted = [Test]::new($psSourceValue.FirstName, $psSourceValue.LastName) Write-Warning "REMOTE EXECUTION NEVER REACHES THIS LINE" return $Converted } } Update-TypeData -TypeName 'Deserialized.Test' -TargetTypeForDeserialization 'Test' Update-TypeData -TypeName 'Test' -TypeConverter 'TestConverter' ($result = [System.Management.Automation.PSSerializer]::Deserialize( [System.Management.Automation.PSSerializer]::Serialize( [Test]::new("Joel","Bennett") ) )) get-member -InputObject $result | out-string | write-host -ForegroundColor DarkCyan }Otherwise Jobs would have been nice
Kagre commentedon Mar 10, 2021
Never mind
-TargetTypeForDeserializationappears to be "working as designed", and so too is the localized randomization of class type names.After mucking about with the localized class naming and the timing of the deserialization declaration, I've finally got the Jobs --if not elegant-- at least working (I'll leave the Invoke-Command, re-rehydration(bihydration?) of a job returned deserialized object, and code cleanup to someone else):
1ramnik commentedon Mar 10, 2021
what is the meaning of stream of bytes?
Please explain a bit.
Kagre commentedon Mar 10, 2021
where are you seeing a "stream of bytes"?
Kagre commentedon Mar 10, 2021
byedration
Stroniax commentedon Jul 12, 2023
This doesn't add up. The example in the blog refers to the IP address conversion. If you look at the type data of
System.Net.IPAddressandDeserialized.System.Net.IPAddress, the data matches up with the instructions provided in the blog. However I am likewise not able to get this to work that way.microsoft-github-policy-service commentedon Jan 9, 2024
This issue has not had any activity in 6 months, if there is no further activity in 7 days, the issue will be closed automatically.
Activity in this case refers only to comments on the issue. If the issue is closed and you are the author, you can re-open the issue using the button below. Please add more information to be considered during retriage. If you are not the author but the issue is impacting you after it has been closed, please submit a new issue with updated details and a link to this issue and the original.
microsoft-github-policy-service commentedon Jan 9, 2024
This issue has not had any activity in 6 months, if there is no further activity in 7 days, the issue will be closed automatically.
Activity in this case refers only to comments on the issue. If the issue is closed and you are the author, you can re-open the issue using the button below. Please add more information to be considered during retriage. If you are not the author but the issue is impacting you after it has been closed, please submit a new issue with updated details and a link to this issue and the original.