哈希表存放的是對(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> $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男
在哈希表中存儲(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> $stuName Value---- -----Books {三國(guó)演義, 圍城, 哈姆雷特}Name 小明Age 12sex 男
在哈希表中插入新的鍵值
在哈希表中插入新的鍵值很方便,象定義變量一樣,可以直接拿來(lái)使用
PS C:Powershell> $Student=@{}PS C:Powershell> $Student.Name="令狐沖"PS C:Powershell> $Student.School="華山派"PS C:Powershell> $StudentName Value---- -----Name 令狐沖School 華山派
哈希表值的更新和刪除
如果要更新鍵的值,可以直接重寫。如果要?jiǎng)h除這個(gè)鍵值對(duì),可以使用Remove方法,參數(shù)為Key
PS C:Powershell> $stuName Value---- -----Books {三國(guó)演義, 圍城, 哈姆雷特}Name 小明Age 12sex 男PS C:Powershell> $stu.Name="趙強(qiáng)"PS C:Powershell> $stu.Name趙強(qiáng)PS C:Powershell> $stu.Remove("Name")PS C:Powershell> $stuName Value---- -----Books {三國(guó)演義, 圍城, 哈姆雷特}Age 12sex 男
使用哈希表格式化輸出
在Powershell中哈希表的一個(gè)有趣的應(yīng)用可以用來(lái)格式化文本輸出。Powershell許多命令的輸出結(jié)果都是以表格的形式,當(dāng)然可以使用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---
上述的命令只能限制表格輸出那些列,隱藏那些列。但是對(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, $column2filename last modification-------- -----------------ABC 2011/11/23 17:25:53myscript 2011/11/29 18:21:28a.html 2011/11/24 18:30:13
|
新聞熱點(diǎn)
疑難解答
圖片精選