Powershell 使用物件與資料結構 (Array, Hash)


  1. Array
    1. Get Element
    2. Set Element
    3. Add Element
    4. Remove Element
    5. Loop Over Elements
    6. Contains, In
  2. Hash
    1. Get Value By Key
    2. Get Keys / Values
    3. Add Element
    4. Remove Element
    5. Loop Over Elements
    6. Clear Hash
  3. 參考資料

筆記 Powershell 的基礎知識,關於如何使用物件與資料結構,包含 Array 陣列以及 Hash 雜湊表。

logo

Array

類似 Python 的 List 或是 JavaScript 的 Array 對於 Element 的 Type 極具彈性。

$array = (1, 3, 5, "egg", "ham", "spam")

Array 的 Index 如同程式語言常見的規則,從 0 開始計數。

Index Value
0 1
1 3
2 5
3 egg
4 ham
5 spam

Get Element

$array[3]
# egg
$array[2..4]
# 5, egg, ham
$array[1,3]
# 3, egg

Set Element

$array[5] = 'maps'

Add Element

因為 Array 是 Immutable,因此 Add 實際上是重新產生一份 Array ,會有執行效能上的影響。

$array.count
# 5
$array = $array += 'new'
$array.count
# 6

Remove Element

因為 Array 是 Immutable 沒有直接的操作方式,只能用 Range Operator 來處理。

# Unshift First Element
$array[1..$array.Length]

# Pop Last Element
$array[0..($array.Length - 2)]

Loop Over Elements

有多種方式可以迭代 Array,包含 Foreach-Object、ForEach Method 以及 foreach Syntax。

$array | % { $_ }

$array.ForEach({ $_ })

foreach ($e in $array)
{
  "$e"
}

Contains, In

檢查 Array 之中是否包含特定的 Element。

$array.Contains('egg')
# True

Hash

類似 Python 的 Dictionary 或是 JavaScript 的 Object,Key-Value Pair 的資料夾結構。

$hash = @{ Name = 'Farfetch''d '; PokeType = 'Normal'; Weight = 33.1; }

Get Value By Key

$hash['Name']
# Farfetch'd 

Get Keys / Values

$hash.Keys
$hash.Values

Add Element

$hash.Add('Category', 'Wild Duck')

或是更直覺的方式 🙂

$hash['Category'] = 'Wild Duck'

Remove Element

$hash.remvoe('Weight')

Loop Over Elements

無法直接 Loop Over Hash,必須要透過 GetEnumerator 來進行內容的迭代。

$hash.GetEnumerator() | % {$_.key + ' : ' + $_.value}

Clear Hash

$hash.clear()

參考資料

您想知道有關於陣列的一切 | Everything you wanted to know about arrays

Powershell Special Characters And Tokens