比较powershell中的两个哈希表 [英] Compare two hashtable in powershell

查看:29
本文介绍了比较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

对于这个条目 $_.Valuedog 所以 $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:

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

这篇关于比较powershell中的两个哈希表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆