How do I list folders and files using the PowerShell tree
command? Is it possible to color format the output for distinct files and folders?
山东弘扬优秀传统文化:文化大省的求索与担当
4 Answers
Simply use tree /F
on any powershell instance to have the same behavior the normal tree
on UNIX has.
The tree
alone on Powershell shows only folders but not files in them.
TREE Drive:\path /F
If command prompt or power shell are not recognizing 'tree', then:
Go to environment variables and change both the user variables and system variables "Path" to C:\Windows\System32
(Mine is C:\Windows\System32
,Find yours using %systemroot%\System32
)
Then open a new power shell and give the above command.
EX:
Is it possible to color format the output for distinct files and folders?
Yes, here's a PowerShell script to list folders and files, color files differently than folders, and adding file size as well as folder size:
function Get-FolderTreeWithSizes {
param (
[string]$Path = ".",
[int]$Indent = 0
)
$items = Get-ChildItem -Path $Path -Force
$folderSize = 0
foreach ($item in $items) {
if ($item.PSIsContainer) {
$subFolderSize = (Get-ChildItem -Path $item.FullName -Recurse -Force | Measure-Object -Property Length -Sum).Sum
$subFolderSizeKB = "{0:N2} KB" -f ($subFolderSize / 1KB)
Write-Host (" " * $Indent + "+-- " + $item.Name + " [Folder] (" + $subFolderSizeKB + ")") -ForegroundColor Green
Get-FolderTreeWithSizes -Path $item.FullName -Indent ($Indent + 4)
} else {
$fileSizeKB = "{0:N2} KB" -f ($item.Length / 1KB)
Write-Host (" " * $Indent + "+-- " + $item.Name + " (" + $fileSizeKB + ")") -ForegroundColor Yellow
$folderSize += $item.Length
}
}
if ($Indent -eq 0) {
Write-Host ("Total Size of '$Path': {0:N2} KB" -f ($folderSize / 1KB)) -ForegroundColor Cyan
}
}
Get-FolderTreeWithSizes
Example output:
I'd note the question asks about the Powershell tree
command. The answers here are for tree.com
, which is a separate executable residing at C:\Windows\System32\tree.com
and hails from the cmd.exe
days. It is unrelated to PowerShell.
There is no PowerShell tree command, though there is a tree
alias in the Powershell Community Extensions, which is an alias of Show-Tree
, and displays files via::
Show-Tree -ShowLeaf
tree /?
."/F Display the names of the files in each folder."
As for colors, superuser isn't a script writing service. If you're stuck with a specific problem and post your code, people here would love to help you.