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

1 Comment

  1. Ravi S. Iyer

    Thanks a ton. I was able to build on the core part of this script to write a script that recursively outputs Get-ChildItem returned object for files and directories of current working directory OR user specified directory but excludes folders and their contents present in $ExcludeFolders variable in script. Usage: script-name [optional-path] | next-cmd .

    For more, please visit my blog post: https://raviswdev.blogspot.com/2024/05/windows-powershell-script-list-files.html or the Gist for above script: https://gist.github.com/ravisiyer/6810da7f41c155f52d3f697df500ec43

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.