Mund
Mund

Reputation: 157

Powershell foreach on two arrays

[Powershell]

There are 2x arrays $arrayRG:

testRG1
testRG2
testRG3

and appropriate $arrayVM:

testVM1
testVM2
testVM3

The problem:

How to run the code below to stop VMs, so values would be taken from arrays, something like:

Stop-AzureRmVM -ResourceGroupName "testRG1" -Name "testVM1"
...

Trying foreach logic, but can not figure out how to grab both values, as below takes only ResourceGroup:

foreach ($VM in $arrayRG)
{
    Stop-AzureRmVM -ResourceGroupName $VM -Name "how to get name here?"
}

------------Other option tried-----------

Using hash tables, but still no luck. Managed to get $hash like this:

Name        Value
testRG1     TestVM1
testRG2     TestVM2
testRG3     TestVM3

when tried foreach on a hash table unsuccessfully:

foreach ($VM in $hash)
{
    Stop-AzureRmVM -ResourceGroupName $VM.Keys -Name $VM.Values
}

Upvotes: 0

Views: 277

Answers (2)

Jawad
Jawad

Reputation: 11364

You can use the hashtable by looking up the keys and then using those to get the values

foreach($key in $hashtable.Keys) {
    $key                  # Prints the name
    $hashtable[$key]      # Prints the value

    Stop-AzureRmVM -ResourceGroupName $key -Name $hashtable[$key]
}

Upvotes: 1

AdminOfThings
AdminOfThings

Reputation: 25001

If there is a one-to-one relationship between the two arrays, you can use a for loop and access the same index in each array:

for ($i = 0; $i -lt $arrayRG.Count; $i++) {
    Stop-AzureRmVM -ResourceGroupName $arrayRG[$i] -Name $arrayVM[$i]
}

You can do something similar with the hash table approach. You just need to enumerate the key pairs first.

$hash.GetEnumerator() | Foreach {
    Stop-AzureRmVM -ResourceGroupName $_.Key -Name $_.Value
}

Upvotes: 2

Related Questions