Foreach Item do Foreach?

Welcome Forums General PowerShell Q&A Foreach Item do Foreach?

This topic contains 4 replies, has 2 voices, and was last updated by

 
Participant
8 months, 2 weeks ago.

  • Author
    Posts
  • #95055

    Participant
    Points: 0
    Rank: Member

    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

    Keymaster
    Points: 1,619
    Helping HandTeam Member
    Rank: Community Hero

    That's exactly how.

  • #95070

    Participant
    Points: 0
    Rank: Member

    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

    Keymaster
    Points: 1,619
    Helping HandTeam Member
    Rank: Community Hero

    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

    Participant
    Points: 0
    Rank: Member

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

The topic ‘Foreach Item do Foreach?’ is closed to new replies.