PowerShell/scripts/list-dir-tree.ps1

81 lines
2.0 KiB
PowerShell
Raw Normal View History

2024-10-01 15:11:03 +02:00
<#
2021-07-13 21:10:02 +02:00
.SYNOPSIS
2024-09-28 13:51:47 +02:00
Lists a dir tree
2021-10-04 21:29:23 +02:00
.DESCRIPTION
2023-08-30 10:28:51 +02:00
This PowerShell script lists all files and folders in a neat directory tree (including icon and size).
2024-09-28 13:51:47 +02:00
.PARAMETER path
2021-10-16 13:40:20 +02:00
Specifies the path to the directory tree
2021-07-13 21:10:02 +02:00
.EXAMPLE
2023-08-30 10:28:51 +02:00
PS> ./list-dir-tree.ps1 C:\MyFolder
📂Results
📄sales.txt (442K)
2023-10-06 12:29:05 +02:00
(2 folders, 1 file, 442K file size in total)
2021-07-13 21:10:02 +02:00
.LINK
https://github.com/fleschutz/PowerShell
2022-01-29 12:47:46 +01:00
.NOTES
2022-09-06 21:42:04 +02:00
Author: Markus Fleschutz | License: CC0
2021-01-29 11:07:01 +01:00
#>
2024-09-28 13:51:47 +02:00
param([string]$path = "$PWD")
2021-01-29 11:07:01 +01:00
2023-08-30 10:28:51 +02:00
function GetFileIcon([string]$suffix) {
switch ($suffix) {
".csv" {return "📊"}
".epub" {return "📓"}
".exe" {return "⚙️"}
".gif" {return "📸"}
".iso" {return "📀"}
".jpg" {return "📸"}
".mp3" {return "🎵"}
".mkv" {return "🎬"}
2024-09-28 13:51:47 +02:00
".png" {return "📸"}
".rar" {return "🎁"}
".tar" {return "🎁"}
".zip" {return "🎁"}
default {return "📄"}
2023-01-09 13:48:04 +01:00
}
}
2023-08-30 10:28:51 +02:00
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"
}
2024-09-28 13:51:47 +02:00
function ListDir([string]$path, [int]$depth) {
2023-08-30 10:28:51 +02:00
$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"
2024-09-28 13:51:47 +02:00
ListDir "$path\$filename" $depth
2021-01-29 11:07:01 +01:00
} else {
2023-08-30 10:28:51 +02:00
$icon = GetFileIcon $item.Extension
Write-Output "$($icon)$filename ($(Bytes2String $item.Length))"
$global:files++
$global:bytes += $item.Length
2021-01-29 11:07:01 +01:00
}
}
2024-09-28 13:51:47 +02:00
$global:folders++
2021-01-29 11:07:01 +01:00
}
try {
2024-09-28 13:51:47 +02:00
[int64]$global:folders = 0
2023-10-06 12:12:58 +02:00
[int64]$global:files = 0
[int64]$global:bytes = 0
2024-09-28 13:51:47 +02:00
ListDir $path 0
Write-Output " ($($global:folders) folders, $($global:files) files, $(Bytes2String $global:bytes) total)"
2021-09-27 10:09:45 +02:00
exit 0 # success
2021-01-29 11:07:01 +01:00
} catch {
2022-04-13 12:06:32 +02:00
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
2021-01-29 11:07:01 +01:00
exit 1
2023-04-27 15:22:28 +02:00
}