locked
recursing folders with get-childitem RRS feed

  • Question

  • I'm at a loss; I'm trying to recurse folders with a break condition (maximum recurse depth; b.t.w. why is this not in get-childitem -recurse?).  So I use get-childitem with my own recursion.

    When I run this script at level 2 it borks with "Cannot find path '<full foldername>' because it does not exist.".  However, one level before during recursion no such error.  The path does exist of course, and it has subfolders.

    Anybody an idea?  I found some scarce remarks around this but nothing I understand.

    Cheers,

    Martin

    ---

    function Get-ScriptDirectory
        {
        $Invocation = (Get-Variable MyInvocation -Scope 1).Value
        Split-Path $Invocation.MyCommand.Path
        }

    function Get-ChildfoldersRecursive
        {
        param( [System.IO.DirectoryInfo]$dir, [int]$recurseasked = 0)
        write-host "DIR at start level $recursecount : $dir"
        $subdirs = get-childitem $dir -force | where { $_.psIsContainer -eq $true }
        if ( $recurseasked -gt $recursecount -and $subdirs.count -gt 0)
            {
            $recursecount += 1
            write-host "SUBDIRS: " $subdirs
            $subdirs | foreach-object `
                {
                write-host "SUBDIR: " $_
                get-childfoldersrecursive "$_" "$recurseasked"
                }
            }
        write-host "DIR at end level " ($recursecount-1) ": $dir"
        }


    $currentdir = Get-ScriptDirectory | get-item
    $recurseasked = 2

    $recursecount = 0
    $folders = get-childfoldersrecursive "$currentdir" "$recurseasked"
    ---

    Thursday, July 7, 2011 1:09 PM

Answers

  • http://stackoverflow.com/questions/4989021/powershell-recursion-with-return/4994219#4994219 -post Keith Hill

    Small mod(only container output):

    function recursive($path, $max, $level = 1)
    {
      $path = (Resolve-Path $path).ProviderPath
      Write-Host "$path - $max - $level"
      foreach ($item in @(Get-ChildItem $path | Where {$_.psiscontainer}))
      {
        if ($level -eq $max) { return }
    
        recursive $item.PSPath $max ($level + 1) 
      }
    }
    


     

    Thursday, July 7, 2011 1:48 PM

All replies

  • http://stackoverflow.com/questions/4989021/powershell-recursion-with-return/4994219#4994219 -post Keith Hill

    Small mod(only container output):

    function recursive($path, $max, $level = 1)
    {
      $path = (Resolve-Path $path).ProviderPath
      Write-Host "$path - $max - $level"
      foreach ($item in @(Get-ChildItem $path | Where {$_.psiscontainer}))
      {
        if ($level -eq $max) { return }
    
        recursive $item.PSPath $max ($level + 1) 
      }
    }
    


     

    Thursday, July 7, 2011 1:48 PM
  • Well that works beautifully thanks a lot, Kazun :)

    Though I'm still wondering what's wrong with my version...

    Thursday, July 7, 2011 3:03 PM