How to jump back into for loop after function ends

This topic contains 3 replies, has 3 voices, and was last updated by  Thomas 9 months, 1 week ago.

  • Author
    Posts
  • #61779

    Thomas
    Participant

    Hi guys

    Got a small problem here that I can't seem to find a solution for, if there is any.
    I am making a script to clean up in a tree structure, i have to delete either $variable1 og $variable2 number of folders.
    But my issue is that I can fine get all the folders into the array, but my for loop stops after it has processed the first folder, how do I return into my for loop again after being out in the function to delete the folders i need?

    I don't really want to have the same code in there twice for just one variable difference, so I had the idea of using a function. I can see that the "return" I have in the function just dumps me out back after my for loop.

    $Folders= Get-ChildItem $Path
    
    function Name1($Variable)
    {
        Checks and deletes some folders
        return
    }
    
    for($i=0; $i -lt ($Folders.Count); $i++)
    {
       if($Folders[$i].Name -eq $SomeName)
       {
        Name1($Variable1)
       }
       ELSE
       {
        Name1($Variable2)
       }
    }
    Write-output "Done cleaning up"
    

    Hope there are someone out here that can push my code in the correct direction 🙂

  • #61782

    Olaf Soyk
    Participant

    Powershell is great in "iterating through arrays" .... 😉

    $Folders= Get-ChildItem $Path
    function Name1($Variable){
        Checks and deletes some folders
        return
    }
    
    foreach($Folder in $Folders){
       if($Folder.Name -eq $SomeName)
       {
          Name1($Variable1)
       }
       ELSE{
          Name1($Variable2)
       }
    }
    Write-output "Done cleaning up"

    That should work actually

  • #61852

    Max Kozlov
    Participant

    want to mention that function call in powershell looks like
    Name1 $Variable
    Name1($Variable) also work in this example but for several parameters it will be
    Name1 $Variable $Variable2, not Name1($Variable, $Variable2) !

    and PS doesn't need return in function body

  • #62000

    Thomas
    Participant

    Thank you Olaf that worked 🙂

You must be logged in to reply to this topic.