0

[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
}

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

awesome, expected something pretty simple, just didn't know the logic. Thank you
1

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]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.