哈希表存放的是對,在哈希表中不再僅僅限制使用數字尋址,可以使用任意類型的數據類型尋址。
創建哈希表
之前使用@()創建數組,現在使用@{}創建哈希表,使用哈希表的鍵訪問對應的值。
PS C:Powershell> $stu=@{ Name = "小明";Age="12";sex="男" }PS C:Powershell> $stuName Value---- -----Name 小明Age 12sex 男PS C:Powershell> $stu["Name"]小明PS C:Powershell> $stu["age"]12PS C:Powershell> $stu.Count3PS C:Powershell> $stu.KeysNameAgesexPS C:Powershell> $stu.Values小明12男
在哈希表中存儲數組
可以在創建哈希表時就使用數組,因為創建數組和哈希表的的元素關鍵字不沖突。一個是逗號,一個是分號。
PS C:Powershell> $stu=@{ Name = "小明";Age="12";sex="男";Books="三國演義","圍城","哈姆雷特" }PS C:Powershell> $stuName Value---- -----Books {三國演義, 圍城, 哈姆雷特}Name 小明Age 12sex 男
在哈希表中插入新的鍵值
在哈希表中插入新的鍵值很方便,象定義變量一樣,可以直接拿來使用
PS C:Powershell> $Student=@{}PS C:Powershell> $Student.Name="令狐沖"PS C:Powershell> $Student.School="華山派"PS C:Powershell> $StudentName Value---- -----Name 令狐沖School 華山派
哈希表值的更新和刪除
如果要更新鍵的值,可以直接重寫。如果要刪除這個鍵值對,可以使用Remove方法,參數為Key
PS C:Powershell> $stuName Value---- -----Books {三國演義, 圍城, 哈姆雷特}Name 小明Age 12sex 男PS C:Powershell> $stu.Name="趙強"PS C:Powershell> $stu.Name趙強PS C:Powershell> $stu.Remove("Name")PS C:Powershell> $stuName Value---- -----Books {三國演義, 圍城, 哈姆雷特}Age 12sex 男
使用哈希表格式化輸出
在Powershell中哈希表的一個有趣的應用可以用來格式化文本輸出。Powershell許多命令的輸出結果都是以表格的形式,當然可以使用Format-Table自定義表格格式,例如:
PS C:Powershell> Dir | Format-Table Directory: C:PowershellMode LastWriteTime Length Name---- ------------- ------ ----d---- 2011/11/23 17:25 ABCd---- 2011/11/29 18:21 myscriptPS C:Powershell> Dir | Format-Table FullName,ModeFullName Mode-------- ----C:PowershellABC d----C:Powershellmyscript d----C:Powershella.html -a---
新聞熱點
疑難解答