在Powershell中创建数组可以使用逗号。

  1. PS C:Powershell> $nums=2,0,1,2
  2. PS C:Powershell> $nums
  3. 2
  4. 0
  5. 1
  6. 2

对于连续的数字数组可以使用一个更快捷的方法

  1. PS C:Powershell> $nums=1..5
  2. PS C:Powershell> $nums
  3. 1
  4. 2
  5. 3
  6. 4
  7. 5

数组的多态

象变量一样如果数组中元素的类型为弱类型,默认可以存储不同类型的值。

  1. PS C:Powershell> $array=1,"2012世界末日",([System.Guid]::NewGuid()),(get-date)
  2. PS C:Powershell> $array
  3. 1
  4. 2012世界末日
  5. Guid
  6. ----
  7. 06a88783-a181-4511-9e41-2780ecbd7924
  8. DisplayHint : DateTime
  9. Date : 2011/12/9 0:00:00
  10. Day : 9
  11. DayOfWeek : Friday
  12. DayOfYear : 343
  13. Hour : 14
  14. Kind : Local
  15. Millisecond : 910
  16. Minute : 15
  17. Month : 12
  18. Second : 45
  19. Ticks : 634590369459101334
  20. TimeOfDay : 14:15:45.9101334
  21. Year : 2011
  22. DateTime : 2011129 14:15:45

空数组和单元素数组

空数组

  1. PS C:Powershell> $a=@()
  2. PS C:Powershell> $a -is [array]
  3. True
  4. PS C:Powershell> $a.Count
  5. 0

1个元素的数组

  1. PS C:Powershell> $a=,"moss"
  2. PS C:Powershell> $a -is [array]
  3. True
  4. PS C:Powershell> $a.Count
  5. 1

强类型数组

Powershell数组一般具有多态性,如果你不指定元素的具体类型,解释器会自动选择合适的类型存储每个元素。如果要统一限制所有元素的类型,可是使用类型名和一对方括号作为数组变量的类型。这样每当赋值时,会自动类型检查。如果目标数据类型不能转换成功,就会抛出一个异常。

  1. PS C:Powershell> [int[]] $nums=@()
  2. PS C:Powershell> $nums+=2012
  3. PS C:Powershell> $nums+=12.3
  4. PS C:Powershell> $nums+="999"
  5. PS C:Powershell> $nums+="can not convert"
  6. Cannot convert value "can not convert" to type "System.Int32". Error: "Input string was not in a correct format."
  7. At line:1 char:6
  8. + $nums <<<< +="can not convert"
  9. + CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException
  10. + FullyQualifiedErrorId : RuntimeException