Search code examples
arrayspowershellhashtable

Powershell Array of hashtables


For example, I have 3 hashtables with different key-values:

$Queue1 = @{
    QueueName = 'MyTestQueue1'
    LockDuration = 'PT1M1'
    AutoDeleteOnIdle = 'P10675199DT2H48M5.4775807S1'
}

$Queue2 = @{
    QueueName = 'MyTestQueue2'
    LockDuration = 'PT1M2'
    AutoDeleteOnIdle = 'P10675199DT2H48M5.4775807S2'
}

$Queue3 = @{
    QueueName = 'MyTestQueue3'
    LockDuration = 'PT1M3'
    AutoDeleteOnIdle = 'P10675199DT2H48M5.4775807S3'
}

Is it possible to combine them in the array and use each key-value inside the foreach?

foreach($hashtable in $Hashtables){
    
    $QueueName = $hashtable.QueueName
    $LockDuration = $hashtable.LockDuration 
    $AutoDeleteOnIdle = $hashtable.AutoDeleteOnIdle
    # Some code here
    }

Solution

  • To declare an array, as portrayed here, you use this syntax:

    $variable = @(element1, element2, element3, ...)
    

    so to create an array for your queues:

    $Hashtables = @($Queue1, $Queue2, $Queue3)
    

    you can also split it over multiple lines, and in that variant the commas are optional:

    $Hashtables = @(
        $Queue1
        $Queue2
        $Queue3
    )