Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PowerShell support HashTable Serialization?

If I want to write an object / HashTable to disk and load it up again later does PowerShell support that?

like image 882
leeand00 Avatar asked Dec 23 '22 18:12

leeand00


2 Answers

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
like image 99
Mathias R. Jessen Avatar answered Jan 18 '23 04:01

Mathias R. Jessen


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
like image 32
iRon Avatar answered Jan 18 '23 04:01

iRon