Foreach Item do Foreach?

This topic contains 4 replies, has 2 voices, and was last updated by  TommyQuality 2 months, 3 weeks ago.

  • Author
    Posts
  • #95055

    TommyQuality
    Participant

    Hi,

    I have a foreach loop on a variable that also contains and array of data. Whats the best way to loop through the first set of data and then foreach item in the next set to do somethings.

    so kinda like

    foreach ($Item in $Data){
     if ($Item.Value -eq "Names"){
     foreach($name in $Item.Value.Names){
        Do-Something .....
        }
      }
    }
    

    Hope this makes sense?

    Cheers

    Tommy

  • #95061

    Don Jones
    Keymaster

    That's exactly how.

  • #95070

    TommyQuality
    Participant

    Cool, thanks Don. Following on from this. If i wanted the script to execute different commands based on the value $Item.Value. What would be the best way.

    I suppose i could use loads of Try statements, maybe something like this...

    foreach ($Item in $Data){
        try {
        if ($Item.Value -eq "Names"){
        foreach($name in $Item.Value.Names){
           Do-Something .....
           }
         }
       }
       Catch{
                Do-Something
            } 
        try {
            if ($Item.Value -eq "Something"){
                foreach($Something in $Item.Value.Something){
                   Do-Something .....
    
            }
        }
    }
        catch {
                Do-Something
             }
        elseif {
                Do-Something
        }
    }
    
    

    Is there a better way?

  • #95076

    Don Jones
    Keymaster

    I'm not following what the Try blocks are meant for...? Just If constructs, or Switch if you've a bunch of different values to test against.

  • #95088

    TommyQuality
    Participant

    Oh Okay. So running multiple "If" constructs is acceptable in a single Try/Catch block?

You must be logged in to reply to this topic.