1

When I execute the following code, assuming X:\ is a multi-level directory tree, it begins to throw strange errors on the second pass.

For example, let's assume X:\ has the following structure

X:\
--1stLevelDir
----2ndLevelDir
--Another1stLevelDir

function recurse{
    param([System.IO.FileSystemInfo] $folder)
    foreach ($dir in GCI $folder -Directory) {
        Write-Output $dir.FullName
        recurse $dir
    }
}

recurse (get-item 'X:\')

That code produces the following output

X:\1stLevelDir
X:\1stLevelDir\2ndLevelDir
GCI : Cannot find path 'X:\2ndLevelDir' because it does not exist.
At foreach line

1 Answer 1

2
recurse $dir.FullName

[IO.DirectoryInfo] objects expand to the short name, which is treated as a relative path - and looked for in the folder you are in.

Edit: or

function recurse{
    param([System.IO.FileSystemInfo] $folder)
    foreach ($dir in GCI $folder.FullName -Directory) {
        Write-Output $dir.FullName
        recurse $dir
    }
}

recurse (get-item 'X:\')
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect thank you, this looses my FileSystemInfo type but I can work without it. Out of curiosity is there a convenient way to maintain that type without making a get-item call?
@Preston yes, put the .FullName in the gci call instead of in the recurse call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.