Using a Queue instead of a Recursion

by Apr 25, 2019

Rather than calling functions recursively, you may at times want to use a Queue object that you can load with fresh tasks while you are unloading things that you have already processed.

Lee Holmes has recently posted the below sample which searches an entire filesystem folder tree without recursive calls:

# create a new queue
$dirs = [System.Collections.Queue]::new()

# add an initial path to the queue
# any folder path in the queue will later be processed
$dirs.Enqueue('c:\windows')

# process all elements on the queue until all are taken
While ($current = $dirs.Dequeue())
{
    # find subfolders of current folder, and if present,
    # add them all to the queue
    try
    {
        foreach ($_ in [IO.Directory]::GetDirectories($current))
        {
                $dirs.Enqueue($_)
        }
    } catch {}

    try
    {
        # find all files in the folder currently processed
        [IO.Directory]::GetFiles($current, "*.exe") 
        [IO.Directory]::GetFiles($current, "*.ps1") 
    } catch { }
} 

The try-catch blocks are required because of the .NET methods used which raise exceptions when you do not have access privileges to files or folders.


psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!