PowerShell/scripts/list-dir-tree.ps1

78 lines
2.0 KiB
PowerShell
Raw Normal View History

2023-10-31 12:33:36 +01:00
<#
2021-07-13 21:10:02 +02:00
.SYNOPSIS
2023-01-06 22:15:14 +01:00
Lists a directory 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).
.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
#>
2023-08-30 10:28:51 +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 "🎬"}
".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"
}
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++
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
}
}
}
try {
2023-10-06 12:12:58 +02:00
[int64]$global:folders = 1
[int64]$global:files = 0
[int64]$global:bytes = 0
2023-08-30 10:28:51 +02:00
ListDirectory $Path 0
2023-10-06 12:29:05 +02:00
Write-Output " ($($global:folders) folders, $($global:files) files, $(Bytes2String $global:bytes) file size in 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
}