If I want to write an object / HashTable to disk and load it up again later does PowerShell support that?
Sure, you can use PowerShell's native CliXml
format:
@{
a = 1
b = [pscustomobject]@{
prop = "value"
}
} | Export-Clixml -Path hashtable.ps1xml
Deserialize with Import-CliXml
:
PS C:\> $ht = Import-CliXml hashtable.ps1xml
PS C:\> $ht['b'].prop -eq 'value'
True
As the default PowerShell hash table (@{...}
) is of type Object
, Object
it doesn't concern just a HashTable
type but the question implies serializing of any (value) type to disk.
In addition to the answer from @Mathias R. Jessen, you might use the PowerShell serializer (System.Management.Automation.PSSerializer) for this:
Serialize to disk
[System.Management.Automation.PSSerializer]::Serialize($HashTable) | Out-File .\HashTable.txt
Deserialize from disk
$PSSerial = Get-Content .\HashTable.txt
$HashTable = [System.Management.Automation.PSSerializer]::Deserialize($PSSerial)
You could also use this ConvertTo-Expression
cmdlet. The downside is that is concerns a non-standard PowerShell cmdlet for serializing but the advantage is that you might use the standard and easy dot-sourcing technique to restore it:
Serialize to disk
$HashTable | ConvertTo-Expression | Out-File .\HashTable.ps1
Deserialize from disk
$HashTable = . .\HashTable.ps1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With