FileSystemSearch.psm1

#region Variables
# Helper variable for BFS Search
$Queue = New-Object System.Collections.ArrayList
#endregion

#region New-FileSystemSearch
Function New-FileSystemSearch
{
    <#
    .SYNOPSIS
 
    Gets all directories under a path
 
    .DESCRIPTION
 
    The New-FileSystemSearch will get all the directories under a path using Breadth-Search-First or Depth-Search-First algorithms.
 
    .PARAMETER Path
 
    The path to search under.
 
    .PARAMETER Method
 
    The method to use. Available options are "BFS" and "DFS". If not specified, DFS will be used.
 
    .EXAMPLE
 
    New-FileSystemSearch -Path d:\tmp -Method DFS
 
    This will list all directories under D:\tmp using DFS
 
    #>


    Param
    (
        [Parameter(Mandatory=$true, Position=0)]
        [string]$Path,

        [Parameter(Mandatory=$false, Position=1)]
        [ValidateSet(“DFS”,”BFS”)] 
        [string]$Method = "DFS"
    )

    # Test if path exists
    if( -Not (Test-Path $Path))
    {
        Write-Error "Could not find path $Path!"
        return
    }

    # Get the full path
    $p = (Resolve-Path $Path).Path

    # Select the method
    if($Method -eq "BFS")
    {    $Queue.Clear()
        _BFS $p
    }
    if($Method -eq "DFS")
    {
        _DFS $p
    }
}
#endregion

#region Helper Functions
# DFS Search function
Function _DFS
{
    Param
    (
        [string]$Path
    )

    # Test if path exists
    if( -Not (Test-Path $Path))
    {
        Write-Error "Could not find path $Path!"
        return
    }

    # Get the full path
    $p = (Resolve-Path $Path).Path

    Write-Output $p

    $directories = Get-ChildItem -Path $p -Directory -Force

    foreach($d in $directories)
    {
        _DFS $d.fullname
    }
}

# BFS Search function
Function _BFS
{
    Param
    (
        [string]$Path
    )

    # Test if path exists
    if( -Not (Test-Path $Path))
    {
        Write-Error "Could not find path $Path!"
        return
    }

    # Get the full path
    $p = (Resolve-Path $Path).Path

    $Queue.Add($p) | Out-Null

    while($Queue.Count -gt 0)
    {
        $directories = Get-ChildItem -Path $Queue[0] -Directory -Force

        foreach($d in $directories)
        {
            $Queue.Add($d.FullName) | Out-Null
        }

        Write-Output $Queue[0]
        $Queue.RemoveAt(0)
    }
}
#endregion

#region Exports
Export-ModuleMember -Function New-FileSystemSearch
#endregion