title: Powershell Recursion with Return
body: <p>I am trying to write a recursive function that will return information in an array, however when I put a return statement into the function it misses certain entries.</p>
  
  <p>I am trying to recursively look through a specified depth of folders getting the acl's associated with the folder. I know getChildItem has a recurse option, but I only want to step through 3 levels of folders.</p>
  
  <p>The excerpt of code below is what I have been using for testing. When getACLS is called without a return statement (commented out below) the results are:</p>
  
  <p>Folder 1</p>
  
  <p>Folder 12</p>
  
  <p>Folder 13</p>
  
  <p>Folder 2</p>
  
  <p>When the return statement is used  I get the following output:</p>
  
  <p>Folder 1</p>
  
  <p>Folder 12</p>
  
  <p>So it looks like the return statement is exiting out from the recursive loop?</p>
  
  <p>The idea is that I want to return a multidimensional array like [folder name, [acls], [[subfolder, [permissions],[[...]]]]] etc.</p>
  
  <pre><code>cls
  
  function getACLS ([string]$path, [int]$max, [int]$current) {
  
      $dirs = Get-ChildItem -Path $path | Where { $_.psIsContainer }
      $acls = Get-Acl -Path $path
      $security = @()
  
      foreach ($acl in $acls.Access) {
          $security += ($acl.IdentityReference, $acl.FileSystemRights)
      }   
  
      if ($current -le $max) {
          if ($dirs) {
              foreach ($dir in $dirs) {
                  $newPath = $path + '\' + $dir.Name
                  Write-Host $dir.Name
     #            return ($newPath, $security, getACLS $newPath $max ($current+1))
     #            getACLS $newPath $max ($current+1)
                  return getACLS $newPath $max ($current+1)
              }   
          }
      } elseif ($current -eq $max ) {
          Write-Host max
          return ($path, $security)
      }
  }
  
  $results = getACLS "PATH\Testing" 2 0
  </code></pre>