Save hash table in PowerShell object notation (PSON)

After 5 years, the cmdlet I had pasted in the original answer has undergone so many updates that it has become completely outdated. Therefore I have replaced the code and the ReadMe with a link to the latest version.

ConvertTo-Expression

The ConvertTo-Expression cmdlet can be download from PowerShell Gallery using the command:

Install-Script -Name ConvertTo-Expression

ReadMe

The full ReadMe (and source code) is available from the GitHub

Answer

Below are some possible options to serialize the specific example (assigned to $Craig) in the question:

ConvertTo-Expression $Craig
@{
    parameters =
        @{
            name = 'parameter 0'
            default = 1
            values =
                1,
                2,
                3,
                4
        },
        @{
            name = 'parameter 1'
            default = 'A'
            values =
                'A',
                'B',
                'C'
        }
    name = 'report 0'
}

To limit the tree view expansion:
(Expand -0 will output a single line and Expand -1 will remove also the unnecessary spaces)

ConvertTo-Expression $Craig -expand 3
@{
    parameters =
        @{name = 'parameter 0'; default = 1; values = 1, 2, 3, 4},
        @{name = 'parameter 1'; default = 'A'; values = 'A', 'B', 'C'}
    name = 'report 0'
}

Preserving the explicit types (strong typed):

ConvertTo-Expression $Craig -expand 3 -Strong
[hashtable]@{
    parameters = [array](
        [hashtable]@{name = [string]'parameter 0'; default = [int]1; values = [array]([int]1, [int]2, [int]3, [int]4)},
        [hashtable]@{name = [string]'parameter 1'; default = [string]'A'; values = [array]([string]'A', [string]'B', [string]'C')}
    )
    name = [string]'report 0'
}

(Note: As per PowerShell design, HashTables are not in order, but if required you might use the [Ordered] type instead.)


Try the *-CliXml cmdlets. To save the object:

@{            
 "name" = "report 0"            
 "parameters" = @(
    @{"name" = "parameter 0"; "default" = 1; "values"=1,2,3,4},
    @{"name" = "parameter 1"; "default" = 'A'; "values" = 'A','B','C'}
    )            
} | Export-Clixml -Path c:\hash.xml

To read it back:

Import-Clixml c:\hash.xml