Skip to content

Instantly share code, notes, and snippets.

@ravisiyer
Last active May 5, 2024 16:05
Show Gist options
  • Save ravisiyer/c12c72edf53c3156bd5d391a5c2c7732 to your computer and use it in GitHub Desktop.
Save ravisiyer/c12c72edf53c3156bd5d391a5c2c7732 to your computer and use it in GitHub Desktop.
PowerShell scripts to recursively list files and directories without using -Recurse parameter for Get-ChildItem
# Recursively lists full path of files and directories of current working directory OR user specified directory
# using write-output.
#
# Usage: script-name [optional-path]
#
# Adapted from Getting files and folders recursively in PowerShell…without using -Recurse!,
# https://cloudrun.co.uk/powershell/getting-files-and-folders-recursively-in-powershell-without-using-recurse/
Param ($path = $pwd)
function get-folders {
Param ($path)
$items = Get-ChildItem -Force $path
foreach ($item in $items) {
# List all the folders
if (($item) -is [System.IO.DirectoryInfo]) {
write-output $path\$item
$itemname = $item.Name
$fullpath = "$path\$itemname"
get-folders $fullpath #Recursively list if it is a directory
}
# Print out any files
if (($item) -is [System.IO.FileInfo]) {
write-output $path\$item
}
}
}
get-folders $path
# Recursively lists full path of files (in yellow) and directories (in green) of current working directory OR
# user specified directory using write-host.
#
# Usage: script-name [optional-path]
#
# Adapted from Getting files and folders recursively in PowerShell…without using -Recurse!,
# https://cloudrun.co.uk/powershell/getting-files-and-folders-recursively-in-powershell-without-using-recurse/
Param ($path = $pwd)
function get-folders {
Param ($path)
$items = Get-ChildItem -Force $path
foreach ($item in $items) {
# List all the folders
if (($item) -is [System.IO.DirectoryInfo]) {
write-host $path\$item -foregroundcolor Green
$itemname = $item.Name
$fullpath = "$path\$itemname"
$array += $fullpath
get-folders $fullpath #Recursively list if it is a directory
}
# Print out any files
if (($item) -is [System.IO.FileInfo]) {
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
@ravisiyer
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment