如何在 PowerShell 中建立字典?


在 PowerShell 中建立字典,我們需要使用來自 .Net 名稱空間 System.Collections.Generic.Dictionary 類。它具有 TKeyTValue。其基本語法為

Dictionary<TKey,TValue>

要了解更多關於此 .Net 名稱空間的資訊,請檢視以下連結。

https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=net-5.0

要建立字典,我們首先將使用資料型別為字典物件類建立物件。在下面的示例中,我們需要新增國家名稱和國家程式碼。因此,我們需要 StringInt。

$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() 方法插入成員。

示例

PS C:\> $Countrydata.Add("India",91)
PS C:\> $Countrydata.Add("Algeria",213)

一旦你檢查值,它的輸出應該以鍵值對的形式呈現。

示例

PS C:\> $Countrydata

輸出

Key     Value
---     -----
India      91
Algeria   213

通常,PowerShell 程式設計師不會使用字典,因為它語法不常見,並且傾向於使用雜湊表,因為雜湊表可以輕鬆建立。

更新於:2020-12-15

11K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.