user2549572
user2549572

Reputation: 99

How to loop through 2 arrays in powershell?

I am fetching the disks along with the vm names to which those disk are attached, then i want save disk name & VM name in a variable as a json. when i run the below code i am not getting the desired output, can someone help me with the correct code.

$disks=Get-AzDisk -ResourceGroupName MFA-RG | where {$_.ManagedBy -ne $null} | select name, managedby
$vmlist=foreach ($name in $disks){
$name.ManagedBy.Split('/')[8]
}
$vmname=foreach ($name in $disks){
$name.Name
}
$vmname=@{}
for($i=0; $i -lt $disks.count; $i++){
$vmname[$i] = $vmlist[$i] }
$vmname | ConvertTo-Json

I am expecting output like

{
"disk 1" : "VM1",
"disk 2" : "VM2"
}

Upvotes: 1

Views: 1585

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25001

You are very close to accomplishing what you want. You need to make a few edits though:

$disks=Get-AzDisk -ResourceGroupName MFA-RG | where {$_.ManagedBy -ne $null} | select name, managedby
$vmlist=foreach ($name in $disks){
$name.ManagedBy.Split('/')[8]
}
$vmname=foreach ($name in $disks){
$name.Name
}
$HashOutput=[ordered]@{}
for($i=0; $i -lt $disks.count; $i++){
$HashOutput[$vmname[$i]] = $vmlist[$i] }
$HashOutput| ConvertTo-Json

You initialized a new hashtable by running $vnname = @{}. This erased everything you had previously stored in $vmname. You can just initialize a new hashtable and use the indexed values of $vmname as your keys.

You must be cautious in this approach as coded because if the number of disks is 1, then accessing $vmname[0] and $vmlist[0] will result in just the first characters of those respective strings. Those variables will be type [string] rather than [array]. I would recommend coding for that condition.

Explanation:

[ordered]@{} signals PowerShell to create a new hashtable object with ordered keys. This means the key/value pairs will output in the order in which they were added to the hash table. $HashOutput[$vmname[$i]] evaluates $i as the current integer value stored in the variable. $vmname will typically be an array type in this case, which means its values are indexed. Since $HashOutput is a hash table, you can add a new key/value pair using the format $HashOutput["<key>"] = "<value>". In the first iteration of the final loop, $i will be 0. Therefore, $vmname[0] will be the first element in that array. That element will become the first key added to the hash table. $vmlist[0] will be the corresponding value added to that key.

Upvotes: 3

Related Questions