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