当前位置: 移动技术网 > IT编程>脚本编程>Shell > Windows Powershell使用哈希表

Windows Powershell使用哈希表

2017年12月08日  | 移动技术网IT编程  | 我要评论

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

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

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---

上述的命令只能限制表格输出那些列,隐藏那些列。但是对于列的宽度,列标题无能为力,但是有了哈希表就可以实现更多自定义了。
表格的每一个列包含四个属性:
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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网