diff --git a/Scripts/list-dir-tree.ps1 b/Scripts/list-dir-tree.ps1 index bcd69674..293cc617 100755 --- a/Scripts/list-dir-tree.ps1 +++ b/Scripts/list-dir-tree.ps1 @@ -2,21 +2,24 @@ .SYNOPSIS Lists a directory tree .DESCRIPTION - This PowerShell script lists all files and folders in a directory tree. -.PARAMETER DirTree + This PowerShell script lists all files and folders in a neat directory tree (including icon and size). +.PARAMETER Path Specifies the path to the directory tree .EXAMPLE - PS> ./list-dir-tree.ps1 C:\ + PS> ./list-dir-tree.ps1 C:\MyFolder + β”œπŸ“‚Results + β”‚ β”œπŸ“„sales.txt (442K) + (2 folders, 1 file, 442K total) .LINK https://github.com/fleschutz/PowerShell .NOTES Author: Markus Fleschutz | License: CC0 #> -param([string]$DirTree = "$PWD") +param([string]$Path = "$PWD") -function GetFileIcon { param([string]$Suffix) - switch ($Suffix) { +function GetFileIcon([string]$suffix) { + switch ($suffix) { ".csv" {return "πŸ“Š"} ".epub" {return "πŸ““"} ".exe" {return "βš™οΈ"} @@ -30,32 +33,43 @@ function GetFileIcon { param([string]$Suffix) } } -function ListDir { param([string]$Directory, [int]$Depth) - $Depth++ - $Items = Get-ChildItem -path $Directory - foreach($Item in $Items) { - $Filename = $Item.Name - for ($i = 1; $i -lt $Depth; $i++) { Write-Host "β”‚ " -noNewline } - if ($Item.Mode -like "d*") { - Write-Host "β”œ" -noNewline - Write-Host -foregroundColor green "πŸ“‚$Filename" - ListDir "$Directory\$Filename" $Depth - $global:Dirs++ +function Bytes2String([int64]$bytes) { + if ($bytes -lt 1000) { return "$bytes bytes" } + $bytes /= 1000 + if ($bytes -lt 1000) { return "$($bytes)K" } + $bytes /= 1000 + if ($bytes -lt 1000) { return "$($bytes)MB" } + $bytes /= 1000 + if ($bytes -lt 1000) { return "$($bytes)GB" } + $bytes /= 1000 + return "$($Bytes)TB" +} + +function ListDirectory([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 } + if ($item.Mode -like "d*") { + Write-Output "β”œπŸ“‚$Filename" + ListDirectory "$path\$filename" $depth + $global:folders++ } else { - $Icon = GetFileIcon $Item.Extension - Write-Host "β”œ$($Icon)$Filename ($($Item.Length) bytes)" - $global:Files++ - $global:Bytes += $Item.Length + $icon = GetFileIcon $item.Extension + Write-Output "β”œ$($icon)$filename ($(Bytes2String $item.Length))" + $global:files++ + $global:bytes += $item.Length } } } try { - [int]$global:Dirs = 1 - [int]$global:Files = 0 - [int]$global:Bytes = 0 - ListDir $DirTree 0 - " ($($global:Dirs) folders, $($global:Files) files, $($global:Bytes) bytes in total)" + [int]$global:folders = 1 + [int]$global:files = 0 + [int]$global:bytes = 0 + ListDirectory $Path 0 + Write-Output " ($($global:folders) folders, $($global:files) files, $(Bytes2String $global:bytes) total)" exit 0 # success } catch { "⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"