How to loop through 2 arrays in powershell?Setting Windows PowerShell environment variablesDetermine installed PowerShell versionTerminating a script in PowerShellHow to run a PowerShell scriptHow to handle command-line arguments in PowerShellPowerShell says “execution of scripts is disabled on this system.”How do I pass multiple parameters into a function in PowerShell?How do you comment out code in PowerShell?How do I concatenate strings and variables in PowerShell?Loop through files in a directory using PowerShell

How do you cope with rejection?

Have I found a major security issue with login

Can a Warforged have a ranged weapon affixed to them like an armblade?

Does ratifying USMCA imply a (stealth) ratification of UNCLOS?

Who is frowning in the sentence "Daisy looked at Tom frowning"?

Was Tyrion always a poor strategist?

Bash - Execute two commands and get exit status 1 if first fails

In How Many Ways Can We Partition a Set Into Smaller Subsets So The Sum of the Numbers In Each Subset Is Equal?

Head-internal relative clauses

Is it possible to view all the attribute data in QGIS

Does science define life as "beginning at conception"?

How was the blinking terminal cursor invented?

Is being an extrovert a necessary condition to be a manager?

How does the probability of events change if an event does not occur

Is my company merging branches wrong?

Is there any official Lore on Keraptis the Wizard, apart from what is in White Plume Mountain?

Bash Read: Reading comma separated list, last element is missed

Precedent for disabled Kings

Greek theta instead of lower case þ (Icelandic) in TexStudio

In Dutch history two people are referred to as "William III"; are there any more cases where this happens?

Warped chessboard

Why would Thor need to strike a building with lightning to attack enemies?

Why is python script running in background consuming 100 % CPU?

How could the B-29 bomber back up under its own power?



How to loop through 2 arrays in powershell?


Setting Windows PowerShell environment variablesDetermine installed PowerShell versionTerminating a script in PowerShellHow to run a PowerShell scriptHow to handle command-line arguments in PowerShellPowerShell says “execution of scripts is disabled on this system.”How do I pass multiple parameters into a function in PowerShell?How do you comment out code in PowerShell?How do I concatenate strings and variables in PowerShell?Loop through files in a directory using PowerShell






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








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"










share|improve this question

















  • 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.

    – postanote
    Mar 23 at 20:08

















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"










share|improve this question

















  • 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.

    – postanote
    Mar 23 at 20:08













1












1








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"










share|improve this question














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"







azure powershell






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 23 at 18:44









user2549572user2549572

2918




2918







  • 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.

    – postanote
    Mar 23 at 20:08












  • 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.

    – postanote
    Mar 23 at 20:08







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.

– postanote
Mar 23 at 20:08





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.

– postanote
Mar 23 at 20:08












1 Answer
1






active

oldest

votes


















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.






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55317192%2fhow-to-loop-through-2-arrays-in-powershell%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    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.






    share|improve this answer





























      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.






      share|improve this answer



























        3












        3








        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.






        share|improve this answer















        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.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 23 at 20:36

























        answered Mar 23 at 20:16









        AdminOfThingsAdminOfThings

        3,1301214




        3,1301214





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55317192%2fhow-to-loop-through-2-arrays-in-powershell%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript