哈希表存放的是對(duì),在哈希表中不再僅僅限制使用數(shù)字尋址,可以使用任意類型的數(shù)據(jù)類型尋址。
創(chuàng)建哈希表
之前使用@()創(chuàng)建數(shù)組,現(xiàn)在使用@{}創(chuàng)建哈希表,使用哈希表的鍵訪問(wèn)對(duì)應(yī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
男
在哈希表中存儲(chǔ)數(shù)組
可以在創(chuàng)建哈希表時(shí)就使用數(shù)組,因?yàn)閯?chuàng)建數(shù)組和哈希表的的元素關(guān)鍵字不沖突。一個(gè)是逗號(hào),一個(gè)是分號(hào)。
PS C:Powershell> $stu=@{ Name = "小明";Age="12";sex="男";Books="三國(guó)演義","圍城","哈姆雷特" }
PS C:Powershell> $stu
Name Value
---- -----
Books {三國(guó)演義, 圍城, 哈姆雷特}
Name 小明
Age 12
sex 男
在哈希表中插入新的鍵值
在哈希表中插入新的鍵值很方便,象定義變量一樣,可以直接拿來(lái)使用
PS C:Powershell> $Student=@{}
PS C:Powershell> $Student.Name="令狐沖"
PS C:Powershell> $Student.School="華山派"
PS C:Powershell> $Student
Name Value
---- -----
Name 令狐沖
School 華山派
哈希表值的更新和刪除
如果要更新鍵的值,可以直接重寫。如果要?jiǎng)h除這個(gè)鍵值對(duì),可以使用Remove方法,參數(shù)為Key
PS C:Powershell> $stu
Name Value
---- -----
Books {三國(guó)演義, 圍城, 哈姆雷特}
Name 小明
Age 12
sex 男
PS C:Powershell> $stu.Name="趙強(qiáng)"
PS C:Powershell> $stu.Name
趙強(qiáng)
PS C:Powershell> $stu.Remove("Name")
PS C:Powershell> $stu
Name Value
---- -----
Books {三國(guó)演義, 圍城, 哈姆雷特}
Age 12
sex 男
使用哈希表格式化輸出
在Powershell中哈希表的一個(gè)有趣的應(yīng)用可以用來(lái)格式化文本輸出。Powershell許多命令的輸出結(jié)果都是以表格的形式,當(dāng)然可以使用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---
上述的命令只能限制表格輸出那些列,隱藏那些列。但是對(duì)于列的寬度,列標(biāo)題無(wú)能為力,但是有了哈希表就可以實(shí)現(xiàn)更多自定義了。
表格的每一個(gè)列包含四個(gè)屬性:
Expression:綁定的表達(dá)式
Width:列寬度
Label:列標(biāo)題
Alignment:列的對(duì)齊方式
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實(shí)現(xiàn)哈希表
- 用Python實(shí)現(xiàn)通過(guò)哈希算法檢測(cè)圖片重復(fù)的教程
- SQL Server2014 哈希索引原理詳解