Getting files and folders recursively in PowerShell…without using -Recurse!

PowerShell

This is a PowerShell script which will traverse a directory structure listing all files and folders, without using the built in -recurse switch.

Now, PowerShell has a built in switch for this using Get-ChildItem C:\temp -Recurse. However, I wanted to see how to do this using a recursive function instead, just to see how the logic would work. Also, once you understand the logic you can then use this in other languages which may not have a switch like -recurse. You can also do other things like colouring the output (in this example folders show in blue and files in yellow), or manipulating data in other ways.

The script works by getting the child files and folders, then if it finds a folder it calls itself. It was a fun little task so here it is.

# You could do it like this, but where's the fun in that? This also returns everything in a single array.
# $folders = Get-ChildItem C:\temp -Recurse
$path = "C:\Temp"
# $ErrorActionPreference = "SilentlyContinue"

function get-folders {
    Param ($path)
    $items = Get-ChildItem $path
    foreach ($item in $items) {
        # List all the folders
        if ($item.Mode -eq "d-----") {
           write-host $path\$item -foregroundcolor Blue
           $itemname = $item.Name
           $fullpath = "$path\$itemname"
           $array += $fullpath
           get-folders $fullpath #Recursively list if it is a directory
        }
        # Print out any files
        if ($item.Mode -eq "-a----") {
            write-host $path\$item -foregroundcolor Yellow
            $itemname = $item.Name
            $fullpath = "$path\$itemname"
            $array += $fullpath
            
         }
}
# Return the array with all subfolders in in case you want to do something else with it
return $array
}

$subfolders = get-folders $path

Posted in PowerShell

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.