- PowerShell 教程
- PowerShell - 首頁
- PowerShell - 概覽
- PowerShell - 環境設定
- PowerShell - 命令
- PowerShell - 檔案和資料夾
- PowerShell - 日期和時間
- PowerShell - 檔案 I/O
- PowerShell - 高階命令
- PowerShell - 指令碼
- PowerShell - 特殊變數
- PowerShell - 運算子
- PowerShell - 迴圈
- PowerShell - 條件
- PowerShell - 陣列
- PowerShell - 雜湊表
- PowerShell - Regex
- PowerShell - 反引號
- PowerShell - 方括號
- PowerShell - 別名
- PowerShell 實用資源
- PowerShell - 快速指南
- PowerShell - 實用資源
- PowerShell - 討論
Powershell - 雜湊表
雜湊表在雜湊表中儲存鍵/值對。使用雜湊表時,指定用作鍵的物件,以及要連結到該鍵的值。通常我們將字串或數字用作鍵。
本教程介紹如何宣告雜湊表變數、建立雜湊表,以及使用其方法處理雜湊表。
宣告雜湊表變數
要在程式中使用雜湊表,您必須宣告一個變數來引用雜湊表。以下是宣告雜湊表變數的語法 −
語法
$hash = @{ ID = 1; Shape = "Square"; Color = "Blue"}
or
$hash = @{}
注意 − 可以使用類似語法來建立有序字典。有序字典維持新增詞條時的順序,而雜湊表則不會。
示例
以下程式碼段是此語法的示例 −
$hash = [ordered]@{ ID = 1; Shape = "Square"; Color = "Blue"}
列印雜湊表。
$hash
輸出
Name Value ---- ----- ID 1 Color Blue Shape Square
雜湊表值透過鍵訪問。
> $hash["ID"] 1
處理雜湊表
使用點表示法可以訪問雜湊表鍵或值。
> $hash.keys ID Color Shape > $hash.values 1 Blue Square
示例
這是一個完整的示例,展示如何建立、初始化和處理雜湊表 −
$hash = @{ ID = 1; Shape = "Square"; Color = "Blue"}
write-host("Print all hashtable keys")
$hash.keys
write-host("Print all hashtable values")
$hash.values
write-host("Get ID")
$hash["ID"]
write-host("Get Shape")
$hash.Number
write-host("print Size")
$hash.Count
write-host("Add key-value")
$hash["Updated"] = "Now"
write-host("Add key-value")
$hash.Add("Created","Now")
write-host("print Size")
$hash.Count
write-host("Remove key-value")
$hash.Remove("Updated")
write-host("print Size")
$hash.Count
write-host("sort by key")
$hash.GetEnumerator() | Sort-Object -Property key
這將產生以下結果 −
輸出
Print all hashtable keys ID Color Shape Print all hashtable values 1 Blue Square Get ID 1 Get Shape print Size 3 Add key-value Add key-value print Size 5 Remove key-value print Size 4 sort by key Name Value ---- ----- Color Blue Created Now ID 1 Shape Square
廣告