PowerShell 是否支持哈希表序列化?

Does PowerShell support HashTable Serialization?

如果我想将对象/哈希表写入磁盘并稍后再次加载它,PowerShell 支持吗?

当然,您可以使用 PowerShell 的 native CliXml format:

@{
  a = 1
  b = [pscustomobject]@{
    prop = "value"
  }
} | Export-Clixml -Path hashtable.ps1xml

反序列化 Import-CliXml:

PS C:\> $ht = Import-CliXml hashtable.ps1xml
PS C:\> $ht['b'].prop -eq 'value'
True

答案可能取决于哈希表中的数据。对于比较简单的数据 Export-ClixmlImport-CliXml 是原生的和直接的 PowerShell解决方案,见另一个答案

对于更复杂的数据,无法通过 CliXml 很好地序列化,但 .NET 可序列化, 您可以使用标准的 .NET 序列化程序之一。例如,BinaryFormatter。 您可以使用(或学习代码)两个现成的脚本:Export-Binary.ps1 and Import-Binary.ps1。 您可以在 Export-Binary.test.ps1.

中找到演示示例,包括哈希表

而且,如果你想有效地存储许多哈希表然后寻找某种 文档存储解决方案。我最近发现 LiteDB 对很多人来说都很好 PowerShell 场景。所以我创建了 Ldbc,LiteDB 的 PowerShell 包装器,包括电池。 使用这种方式,您可以存储和检索数千个哈希表。

更新:如果您更喜欢以 PSD1(本机 PowerShell 数据格式)存储相对简单的数据,您也可以使用脚本模块PsdKit。 (谢谢@iRon 提醒)

由于默认的 PowerShell 散列 table (@{...}) 是 Object 类型,Object 它不仅仅涉及 HashTable 类型,而且这个问题意味着将 any(值)类型序列化到磁盘。

除了 @Mathias R. Jessen, you might use the PowerShell serializer (System.Management.Automation.PSSerializer) 的回答之外:

序列化到磁盘

[System.Management.Automation.PSSerializer]::Serialize($HashTable) | Out-File .\HashTable.txt

从磁盘反序列化

$PSSerial = Get-Content .\HashTable.txt
$HashTable = [System.Management.Automation.PSSerializer]::Deserialize($PSSerial)

您也可以使用此 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 技术来恢复它:

序列化到磁盘

$HashTable | ConvertTo-Expression | Out-File .\HashTable.ps1

从磁盘反序列化

$HashTable = . .\HashTable.ps1