比较powershell中的两个哈希表 [英] Compare two hashtable in powershell
问题描述
您好,我是初学者,我需要比较两个哈希表并重新生成另一个.
Hello i'm beginner and I need to compare two hashtable and to have an other respawn.
例如:
[hashtable]$alpha =@{
"A1" = "computer";
"A2" = "folder";
"A3" = "plane";
"A4" = "flower";
"A5" = "dog";
}
[hashtable]$beta =@{
"computer" = "P1";
"plane" = "P2";
"garden" = "p3";
"flower" = "P4";
"dog" = "P5";
}
如果我在 $alpha
和 $beta
中有计算机,我需要为用户 A1 编写 P1如果我在 $alpha
和 $beta
中有飞机,我需要为用户 A3 编写 P2
if i have Computer in $alpha
and in $beta
i need to write P1 for the user A1
if i have plane in $alpha
and in $beta
i need to write P2 for the user A3
我需要为每个使用吗?
谢谢!
推荐答案
解决方案已经由 @PetSerAl 提供和 @LotPings 并且是以下之一
The solution has been already provided by @PetSerAl and @LotPings and is one of the following
$alpha.GetEnumerator() | select Key, @{ n='Value'; e={$beta[$_.Value]} }
$alpha.GetEnumerator() | %{[PSCustomObject]@{aKey=$_.Key;aValue=$_.Value;bValue=$beta[$_.Value]}}
让我解释一下到底发生了什么.
Let me explain what exactly happens there.
首先,当您使用哈希表时,您无法使用像 Select-Object
这样的 cmdlet 直接操作它们.为此,您需要对其使用 GetEnumerator()
方法.现在您可以将其通过管道传送到 Select-Object
.
First of all, as you use hashtables you cannot manipulate them directly using cmdlets like Select-Object
. In order to do this you need to use GetEnumerator()
method on it. Now you can pipe it to Select-Object
.
要使用另一个哈希表中的值,您必须使用计算属性而不是标准属性.它的语法是:
To use the values from another hashtable you have to use calculated property instead of standard one. The syntax of it is:
@{ n='name'; e={ expression to be executed }
让我们深入研究一下这个表达式$beta[$_.Value]
.$_
表示发送到管道的对象,因此 $_.Value
是它的值(如您所知,哈希表具有键名和值).为了更好地理解检查这个表达式及其结果
Let's dig into this expression $beta[$_.Value]
a bit more. $_
represents the object sent to pipeline so $_.Value
is its value (as you know hashtables have key names and values). To better understand check this expression and its result
PS C:> $alpha.GetEnumerator() | select -Last 1
Name Value
---- -----
A5 dog
对于这个条目 $_.Value
是 dog
所以 $beta[$_.Value]
被评估为 $beta["dog"]
其值为:
For this entry $_.Value
is dog
so $beta[$_.Value]
is evaluated to $beta["dog"]
and its value is:
PS C:> $beta["dog"]
P5
<小时>
其他资源:
Additional resources:
这篇关于比较powershell中的两个哈希表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!