Windows Powershell使用哈希表

2019-09-30 14:13:10王旭

哈希表存放的是对,在哈希表中不再仅仅限制使用数字寻址,可以使用任意类型的数据类型寻址。

创建哈希表
之前使用@()创建数组,现在使用@{}创建哈希表,使用哈希表的键访问对应的值。

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
男

在哈希表中存储数组

可以在创建哈希表时就使用数组,因为创建数组和哈希表的的元素关键字不冲突。一个是逗号,一个是分号。

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方法,参数为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许多命令的输出结果都是以表格的形式,当然可以使用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---