powershell - 键和值的哈希集

标签 powershell hashset

我的脚本有问题:

这里我设置了一个var remotefilehash:

$remotefilehash = $remotefiles -replace '^[a-f0-9]{32}(  )', '$0=  ' | ConvertFrom-StringData

这会创建一个哈希表

然后我将这些哈希值与本地哈希集中的值进行比较

# Create a hash set from the local hashes.

$localHashSet = [System.Collections.Generic.HashSet[string]] $localmd5

# Loop over all remote hashes to find those not among the local hashes.
$diffmd5 = $remotefilehash.Keys.Where({ -not $localHashSet.Contains($_) })

这为我提供了哈希键,但我随后还需要获取在上面找到的那些键的哈希值......

最佳答案

this creates a hashtable

实际上,它创建了一个 hashtables数组 ,因为ConvertFrom-StringData每个管道输入对象转换为一个单独的哈希表。

要创建单个哈希表,请首先连接输入行以形成单个字符串 - 请注意-join“`n”的方式应用于 -replace 操作的结果以形成单个多行字符串:

$remotefilehash = 
  ($remotefiles -replace '^[a-f0-9]{32}(  )', '$0=  ' -join "`n") |
     ConvertFrom-StringData

要枚举哈希表(类似)对象的键值对,而不仅仅是枚举 (.Keys),您可以需要使用其 .GetEnumerator() 方法:

$diffmd5 = 
  $remotefilehash.GetEnumerator().Where({ -not $localHashSet.Contains($_.Key) })

必须明确请求枚举器的原因是,PowerShell 默认情况下将哈希表/字典视为一个单个对象,作为一个整体传递 em> 通过管道/传递给枚举方法如.Where().ForEach()数组方法。

请注意,上述命令的输出本身不是哈希表,而是一个常规的类似数组的集合(类型为 [System.Collections.ObjectModel.Collection[psobject] ),其元素恰好是键值对对象。
因此,该输出在管道中被枚举。

关于powershell - 键和值的哈希集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69782447/

相关文章:

bash - bash 中的哈希集或关联数组

java - 从 HashSet 中提取任意元素的性能(运行时)

java - 哈希集在java中获取空字符串作为元素

azure - 获取 Azure Devops Pipeline 中分支的名称

powershell - 如何使用Powershell关闭现有IE窗口中的选项卡

java - 获取对 Set 中重复项的引用

java - 为什么HashSet或HashMap不支持基于位置的访问?然而,这些类还将对象存储在 Enter 类型的数组中

regex - 使用 PowerShell 从文本段落中提取 6 位数字字符串导致空白数据

powershell - 如何使用 powershell 将 "\"替换为 "\\"?

azure - 如何使用 Azure CLI 从 Azure IoT 中心删除所有设备?