Skip to content

Instantly share code, notes, and snippets.

@gaelcolas
Created September 3, 2016 10:48
Show Gist options
  • Save gaelcolas/11c0779ac237e3711de0fe2cd513a486 to your computer and use it in GitHub Desktop.
Save gaelcolas/11c0779ac237e3711de0fe2cd513a486 to your computer and use it in GitHub Desktop.
$deserialized = [psobject][ordered]@{
'string' = 'this is a string'
'double' = [double]::MaxValue
'fileInfo' = 'C:\'
'__castme' = {
param($myself)
switch (($myself|Get-Member -MemberType NoteProperty).Name)
{
'string' {$myself.string = $myself.string }
'double' {$myself.double = [double]($myself.double) }
'fileInfo' {$myself.fileInfo = [System.IO.FileInfo]($myself.fileInfo) }
'__castme' { $myself.__castme = [scriptblock]::create($myself.__castme) }
}
$myself
}.ToString()
} | convertTo-Json | convertfrom-json
$casted = [scriptblock]::Create($deserialized.__castme).invoke($deserialized)
"string is of type $($casted.string.GetType().ToString())"
"Double is of type $($casted.double.GetType().ToString())"
"FileInfo is of type $($casted.fileInfo.GetType().ToString())"
"__castme is of type $($casted.__castme.GetType().ToString())"
#This is a simple example, you can use the castme to also 'reload' script method,
# or PSTypeName
# I usually wrap this up into a New-something function, that allows to create such
# serializable object with strongly typed parameters, and to also allow piping
# deserialized object to it...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment