CodeToLive

PowerShell Arrays & Hashtables

Arrays and hashtables are fundamental data structures in PowerShell for storing and organizing collections of data.

Arrays

Arrays are ordered collections of items that can be accessed by index.

Creating Arrays

# Simple array
$fruits = "Apple", "Banana", "Orange"
$numbers = 1, 2, 3, 4, 5

# Using array subexpression
$services = @(Get-Service)

# Range operator
$sequence = 1..10

# Empty array
$emptyArray = @()

# Typed array
[int[]]$intArray = 1, 2, 3

Accessing Array Elements

# Indexing (0-based)
$firstFruit = $fruits[0]  # Apple
$lastFruit = $fruits[-1]  # Orange

# Slicing
$someFruits = $fruits[0..1]  # Apple, Banana
$everyOther = $numbers[0..$numbers.Length..2]  # 1, 3, 5

# Count/Length
$itemCount = $fruits.Count

Modifying Arrays

# Adding elements
$fruits += "Grape"  # Creates new array
$fruits = $fruits + "Mango"

# Removing elements (filtering)
$fruits = $fruits | Where-Object { $_ -ne "Banana" }

# Modifying elements
$fruits[1] = "Blueberry"

Array Methods

# Sorting
$sorted = $fruits | Sort-Object
[array]::Sort($numbers)

# Searching
$index = [array]::IndexOf($fruits, "Orange")
$containsApple = $fruits -contains "Apple"

# Filtering
$filtered = $fruits | Where-Object { $_.Length -gt 5 }

# ForEach method
$fruits.ForEach({ $_.ToUpper() })

Hashtables

Hashtables are key-value pairs that provide fast lookup capabilities.

Creating Hashtables

# Basic hashtable
$person = @{
    Name = "John Doe"
    Age = 30
    Occupation = "Developer"
}

# Ordered hashtable (preserves insertion order)
$ordered = [ordered]@{
    First = 1
    Second = 2
    Third = 3
}

# Empty hashtable
$emptyHash = @{}

Accessing Hashtable Elements

# Dot notation
$name = $person.Name

# Index notation
$age = $person["Age"]

# All keys/values
$keys = $person.Keys
$values = $person.Values

# Checking existence
$hasName = $person.ContainsKey("Name")
$has30 = $person.ContainsValue(30)

Modifying Hashtables

# Adding items
$person["Location"] = "New York"
$person.Country = "USA"

# Removing items
$person.Remove("Occupation")

# Updating values
$person.Age = 31

Hashtable Methods

# Cloning
$clone = $person.Clone()

# Enumerating
$person.GetEnumerator() | ForEach-Object {
    "Key: $($_.Key), Value: $($_.Value)"
}

# Converting to/from arrays
$arrayFromHash = $person.GetEnumerator() | ForEach-Object { "$($_.Key)=$($_.Value)" }
$hashFromArray = @{}
1..3 | ForEach-Object { $hashFromArray["Key$_"] = "Value$_" }

Working with Collections

ArrayList (Mutable Alternative)

# More efficient for frequent modifications
$list = [System.Collections.ArrayList]@(1,2,3)
$list.Add(4) | Out-Null
$list.Remove(2) | Out-Null
$list.RemoveAt(0)

Generic Lists

# Strongly typed lists
$intList = [System.Collections.Generic.List[int]]@(1,2,3)
$intList.Add(4)
$intList.Remove(2)

Custom Objects vs Hashtables

# PSCustomObject (better for output)
$personObj = [PSCustomObject]@{
    Name = "Jane"
    Age = 25
    Title = "Manager"
}

# Hashtable (better for internal processing)
$personHash = @{
    Name = "Jane"
    Age = 25
    Title = "Manager"
}

Practical Examples

Grouping Data

# Group processes by company
$processGroups = Get-Process | Group-Object Company -AsHashTable

# Access grouped data
$processGroups["Microsoft Corporation"] | Select-Object Name, CPU

Configuration Storage

$config = @{
    Settings = @{
        LogLevel = "Verbose"
        MaxRetries = 3
        Timeout = 30
    }
    Servers = @("Server1", "Server2", "Server3")
}

# Access nested values
$logLevel = $config.Settings.LogLevel

Counting Occurrences

$words = "apple", "banana", "apple", "orange", "banana", "apple"
$wordCount = @{}

foreach ($word in $words) {
    if ($wordCount.ContainsKey($word)) {
        $wordCount[$word]++
    } else {
        $wordCount[$word] = 1
    }
}

$wordCount