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"
---