比较powershell中的两个哈希表

Sno*_*ung 2 powershell compare hashtable powershell-2.0

您好,我是初学者,我需要比较两个哈希表并进行其他重生。

例如 :

[hashtable]$alpha =@{
"A1" = "computer";
"A2" = "folder";
"A3" = "plane";
"A4" = "flower";
"A5" = "dog";
}


[hashtable]$beta =@{
"computer" = "P1";
"plane" = "P2";
"garden" = "p3";
"flower" = "P4";
"dog" = "P5";
}
Run Code Online (Sandbox Code Playgroud)

如果我有电脑$alpha$beta我需要编写P1用户A1,如果我在有平面$alpha$beta我需要写P2用户A3

我需要为每个使用吗?

谢谢 !

rob*_*bdy 6

该解决方案已由@PetSerAl@LotPings提供,并且是以下解决方案之一

$alpha.GetEnumerator() | select Key, @{ n='Value'; e={$beta[$_.Value]} }
$alpha.GetEnumerator() | %{[PSCustomObject]@{aKey=$_.Key;aValue=$_.Value;bValue=$beta[$_.Value]}}
Run Code Online (Sandbox Code Playgroud)

让我解释一下那里到底发生了什么。

首先,当您使用哈希表时,您不能直接使用 cmdlet 来操作它们,例如Select-Object. 为了做到这一点,你需要GetEnumerator()对它使用方法。现在您可以将其通过管道传输到Select-Object.

要使用来自另一个哈希表的值,您必须使用计算属性而不是标准属性。它的语法是:

@{ n='name'; e={ expression to be executed }
Run Code Online (Sandbox Code Playgroud)

让我们更深入地研究这个表达式$beta[$_.Value]$_表示发送到管道的对象,$_.Value它的值也是(如您所知,哈希表具有键名和值)。为了更好地理解检查这个表达式及其结果

PS C:\> $alpha.GetEnumerator() | select -Last 1

Name                           Value
----                           -----
A5                             dog
Run Code Online (Sandbox Code Playgroud)

对于此条$_.Value目,dog因此$beta[$_.Value]评估为$beta["dog"],其值为:

PS C:\> $beta["dog"]
P5
Run Code Online (Sandbox Code Playgroud)

其他资源:

  1. 微代码:PowerShell 脚本技巧:在 Windows PowerShell 中使用哈希表的乐趣
  2. 在 PowerShell 中使用 Select-Object 添加计算属性
  3. 相同但要替换多个值的示例(我的回答)