哈希表存放的是對,在哈希表中不再僅僅限制使用數(shù)字尋址,可以使用任意類型的數(shù)據(jù)類型尋址。
創(chuàng)建哈希表
之前使用@()創(chuàng)建數(shù)組,現(xiàn)在使用@{}創(chuàng)建哈希表,使用哈希表的鍵訪問對應的值。
PS C:Powershell> $stu=@{ Name = "小明";Age="12";sex="男" }
PS C:Powershell> $stu
Name Value
---- -----
Name 小明
Age 12
sex 男
PS C:Powershell> $stu["Name"]
小明
PS C:Powershell> $stu["age"]
12
PS C:Powershell> $stu.Count
3
PS C:Powershell> $stu.Keys
Name
Age
sex
PS C:Powershell> $stu.Values
小明
12
男
在哈希表中存儲數(shù)組
可以在創(chuàng)建哈希表時就使用數(shù)組,因為創(chuàng)建數(shù)組和哈希表的的元素關(guān)鍵字不沖突。一個是逗號,一個是分號。
PS C:Powershell> $stu=@{ Name = "小明";Age="12";sex="男";Books="三國演義","圍城","哈姆雷特" }
PS C:Powershell> $stu
Name Value
---- -----
Books {三國演義, 圍城, 哈姆雷特}
Name 小明
Age 12
sex 男
在哈希表中插入新的鍵值
在哈希表中插入新的鍵值很方便,象定義變量一樣,可以直接拿來使用
PS C:Powershell> $Student=@{}
PS C:Powershell> $Student.Name="令狐沖"
PS C:Powershell> $Student.School="華山派"
PS C:Powershell> $Student
Name Value
---- -----
Name 令狐沖
School 華山派
哈希表值的更新和刪除
如果要更新鍵的值,可以直接重寫。如果要刪除這個鍵值對,可以使用Remove方法,參數(shù)為Key
PS C:Powershell> $stu
Name Value
---- -----
Books {三國演義, 圍城, 哈姆雷特}
Name 小明
Age 12
sex 男
PS C:Powershell> $stu.Name="趙強"
PS C:Powershell> $stu.Name
趙強
PS C:Powershell> $stu.Remove("Name")
PS C:Powershell> $stu
Name Value
---- -----
Books {三國演義, 圍城, 哈姆雷特}
Age 12
sex 男
使用哈希表格式化輸出
在Powershell中哈希表的一個有趣的應用可以用來格式化文本輸出。Powershell許多命令的輸出結(jié)果都是以表格的形式,當然可以使用Format-Table自定義表格格式,例如:
PS C:Powershell> Dir | Format-Table
Directory: C:Powershell
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 2011/11/23 17:25 ABC
d---- 2011/11/29 18:21 myscript
PS C:Powershell> Dir | Format-Table FullName,Mode
FullName Mode
-------- ----
C:PowershellABC d----
C:Powershellmyscript d----
C:Powershella.html -a---
上述的命令只能限制表格輸出那些列,隱藏那些列。但是對于列的寬度,列標題無能為力,但是有了哈希表就可以實現(xiàn)更多自定義了。
表格的每一個列包含四個屬性:
Expression:綁定的表達式
Width:列寬度
Label:列標題
Alignment:列的對齊方式
PS C:Powershell> $column1 = @{expression="Name"; width=30;label="filename"; alignment="left"}
PS C:Powershell> $column2 = @{expression="LastWriteTime"; width=40;label="last modification"; alignment="right"}
PS C:Powershell> ls | Format-Table $column1, $column2
filename last modification
-------- -----------------
ABC 2011/11/23 17:25:53
myscript 2011/11/29 18:21:28
a.html 2011/11/24 18:30:13
您可能感興趣的文章:- js中哈希表的幾種用法總結(jié)
- php內(nèi)核解析:PHP中的哈希表
- python實現(xiàn)哈希表
- 用Python實現(xiàn)通過哈希算法檢測圖片重復的教程
- SQL Server2014 哈希索引原理詳解