JSON Serialization Options
In the previous article in this series, we explored PowerShell serialization. This is the process of converting an object into a format that can be stored or transmitted, typically via a file. PowerShell does this automatically in remoting situation. You can obtain the best fidelity by using the Export-CliXml
and Import-CliXml
cmdlets. These cmdlets serialize and deserialize objects to and from XML files. This is a great way to store objects in a file and retrieve them later. The format includes key type information, so you can be sure that the object will be reconstituted correctly with minimal effort.
Another option you might consider is JSON. This is a lighter-weight format that is more human-readable than XML. PowerShell has built-in cmdlets to convert objects to and from JSON. The ConvertTo-Json
cmdlet converts an object to a JSON string, and the ConvertFrom-Json
cmdlet converts a JSON string back to an object. In order to know when to use JSON for serialization over other alternatives, you need to understand the limitations.
Let's start with a relatively simple object.
$o = Get-Service bits | Select Name,Status,DisplayName,StartType,
@{Name="ComputerName";Expression={$env:COMPUTERNAME}},
@{Name="Date";Expression={(Get-Date)}}