本文介绍了在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 A1if 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:

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

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

07-29 11:58