如何在PowerShell中创建字典?
要在PowerShell中创建字典,我们需要使用.Net命名空间System.Collections.Generic中的类Dictionary。 它具有TKey和TValue。它的基本语法是
Dictionary<TKey,TValue>
要了解有关此.Net命名空间的更多信息,请查看下面的链接。
https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.dictionary-2?view=net-5.0
要创建字典,我们将首先使用数据类型为字典对象类创建对象。在下面的示例中,我们需要添加国家/地区名称和国家/地区代码。所以我们需要String和Int。
$countrydata = New-Object System.Collections.Generic.Dictionary"[String,Int]"
一旦我们检查了$countrydata变量的类型,它应该是字典。例如,
示例
PS C:\> $Countrydata.GetType() | ft -AutoSize输出结果
IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Dictionary`2 System.Object
让我们检查一下可用的方法。
示例
PS C:\> $Countrydata | Get-Member -MemberType Method | Select Name, Membertype输出结果
Name MemberType ---- ---------- Add Method Clear Method Contains Method ContainsKey Method ContainsValue Method CopyTo Method EnsureCapacity Method Equals Method GetEnumerator Method GetHashCode Method GetObjectData Method GetType Method OnDeserialization Method Remove Method ToString Method TrimExcess Method TryAdd Method TryGetValue Method
因此,我们可以使用Add()method插入成员。
示例
PS C:\> $Countrydata.Add("India",91)
PS C:\> $Countrydata.Add("Algeria",213)检查该值后,其输出应在“键-值”对中。
示例
PS C:\> $Countrydata输出结果
Key Value --- ----- India 91 Algeria 213
通常,PowerShell程序员由于其语法不常用而不会使用该目录,而是倾向于使用Hashtable,因为它易于创建。
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短