Author Posts

January 12, 2017 at 1:50 pm

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 🙂

January 12, 2017 at 2:04 pm

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

January 13, 2017 at 7:02 am

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

January 16, 2017 at 8:35 am

Thank you Olaf that worked 🙂