简体   繁体   中英

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
}

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM