Improved list-dir-tree.ps1

This commit is contained in:
Markus Fleschutz
2025-07-26 15:51:13 +02:00
parent 4e8439b050
commit 1e74da1e5d

View File

@ -1,15 +1,15 @@
<#
.SYNOPSIS
Lists a dir tree
Lists a directory tree
.DESCRIPTION
This PowerShell script lists all files and folders in a neat directory tree (including icon and size).
This PowerShell script lists all files and folders in a directory tree (including icon and size).
.PARAMETER path
Specifies the path to the directory tree
Specifies the file path to the directory tree
.EXAMPLE
PS> ./list-dir-tree.ps1 C:\MyFolder
├📂Results
│ ├📄sales.txt (442K)
(2 folders, 1 file, 442K file size in total)
(2 folders, 1 file, 442K total)
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
@ -49,32 +49,30 @@ function Bytes2String([int64]$bytes) {
}
function ListDir([string]$path, [int]$depth) {
$depth++
$items = Get-ChildItem -path $path
foreach($item in $items) {
$filename = $item.Name
for ($i = 1; $i -lt $depth; $i++) { Write-Host "" -noNewline }
Write-Host " " -noNewline
for ([int]$i = 1; $i -lt $depth; $i++) { Write-Host " " -noNewline }
if ($item.Mode -like "d*") {
Write-Output "├📂$Filename"
ListDir "$path\$filename" $depth
Write-Host "├📂$($item.Name)"
ListDir "$path\$($item.Name)" ($depth + 1)
} else {
$icon = GetFileIcon $item.Extension
Write-Output "$($icon)$filename ($(Bytes2String $item.Length))"
Write-Host "$(GetFileIcon $item.Extension)$($item.Name) ($(Bytes2String $item.Length))"
$global:files++
$global:bytes += $item.Length
}
}
$global:folders++
if ($depth -gt $global:depth) { $global:depth = $depth }
}
try {
[int64]$global:folders = 0
[int64]$global:files = 0
[int64]$global:bytes = 0
ListDir $path 0
Write-Output " ($($global:folders) folders, $($global:files) files, $(Bytes2String $global:bytes) total)"
Write-Host "`n 📂$path"
[int64]$global:files = $global:folders = $global:depth = $global:bytes = 0
ListDir $path 1
" ($($global:files) files, $($global:folders) folders, depth $($global:depth), $(Bytes2String $global:bytes) total)"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
"⚠️ ERROR: $($Error[0]) in script line $($_.InvocationInfo.ScriptLineNumber)."
exit 1
}