1

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"
}
1
  • 1
    What is the output you are getting? If you run just segments of the code, one at time. What results are yo getting? Meaning, running $disks, what is returned, then running $vmlist, what gets returned? ... and so on. Commented Mar 23, 2019 at 20:08

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

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.