Powershell数组和哈希表

# Powershell数组和哈希表

# 命令的返回值可以作为一个数组存储
# $ipconfig=ipconfig
# $ipconfig

# 使用数组存储结果
# 可以判断一个变量是否为数组
# $ip=ipconfig
# $ip -is [array]
# "abcd" -is [array]
# $str="aaaa"
# $str.ToCharArray() -is [array]
# $str.ToCharArray().Count
# $str.ToCharArray()[0]

# 数组的每一个元素存放的是一个System.IO.DirectoryInfo对象。
# 对于任何一个对象都可以使用Format-List * 查看它所有的属性和方法。

# 创建数组
# 在Powershell中创建数组可以使用逗号。
# $nums=1,2,3,4;
# $nums

# 对于连续的数字数组可以这样创建
# $nums=1..10
# $nums


# 数组的多态
# 象变量一样如果数组中元素的类型为弱类型,默认可以存储不同类型的值。
# $array=1,"2012世界末日",([System.Guid]::NewGuid()),(get-date)
# $array


# 空数组和单元素数组
# 空数组
# $arr = @()
# $arr -is [array]
# $arr.Count

#1个元素的数组
# $arr = ,"moss"
# $arr -is [array]
# $arr.Count

# Powershell访问数组
# 数组的元素可以使用索引寻址,第一个元素的索引为0
# 第i个元素的索引为i-1,最后一个元素的索引为Count-1
# Powershell为了使用方便,直接可以将 -1 作为最后的一个元素的索引。
# $books="book1","book2","book3","book4"
# $books[0]
# $books[-1]
# $books.Count
# $books[$books.Length-1]
# $books[$books.Count-1]

# 从数组中选择多个元素
# $result=ls
# $result[0,5,2]

# 数组的逆序输出
# $books="book1","book2","book3","book4"
# $books[($books.Count)..0]

# 给数组添加和删除元素
# 因为Powershell数组在内存中是顺序存储的,所以数组的大小必须是确定的,这样才方便分配存储空间,所以给数组增加元素其实相当于创建一个新的数组,
# 只不过之后会把原来的副本删除。在当前数组追加元素可以使用“+=”操作符
# $books="book1","book2","book3","book4"
# $books += "book5"
# $books

# 删除中间的元素
# $num=1..4
# $num=$num[0..1]+$num[3]
# $num
# 0..1是下标


# Powershell复制数组
# 数组属于引用类型,使用默认的的赋值运算符在两个变量之间赋值只是复制了一个引用,两个变量共享同一份数据。
# 复制数组最好使用Clone()方法,除非有特殊需求。
# $chs=@("A","B","C")
# $chsBak=$chs
# $chsBak[1]="H"
# $chs
#
# $chs.Equals($chsBak)

# $chsNew=$chs.Clone()
# $chsNew[1]="good"
# $chs.Equals($chsNew)
# $chs


# Powershell强类型的数组
# [int[]]$num=@()
# $num+=1
# $num+=2
# $num+="5"
# $num+="霓虹"
# $num

# Powershell使用哈希表
# 创建哈希表
# $stu=@{name="naacy";age=1;sex="man"}
# $stu["name"]
# $stu.Count
# $stu.Keys
# $stu.Values

# 在哈希表中存储数组
# $stu=@{ Name = "小明";Age="12";sex="男";Books="三国演义","围城","哈姆雷特" }
# $stu

# 在哈希表中插入新的键值
# $students=@{}
# $students.Name="xixoqi"
# $students

# 使用哈希表格式化输出
# Dir | Format-Table fullname,mode

# 表格的每一个列包含四个属性:
# Expression:绑定的表达式
# Width:列宽度
# Label:列标题
# Alignment:列的对齐方式

$column1 = @{expression="Name"; width=20;label="filename"; alignment="left"}
$column2 = @{expression="LastWriteTime"; width=40;label="last modification"; alignment="right"}
ls | Format-Table $column1, $column2

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章