This is a PowerShell script which will traverse a directory structure listing all files and folders, without using the built-in -Recurse switch.
PowerShell has a built-in switch for this using Get-ChildItem C:\temp -Recurse. However, this script shows how to do it using a recursive function instead — useful for understanding the logic and applying it to other languages that may not have a recurse switch.
The script works by getting the child files and folders, then if it finds a folder it calls itself.
$path = "C:\Temp"
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
return $array
}
$subfolders = get-folders $path
The script outputs folders in blue and files in yellow, making it easy to distinguish between them at a glance.