# ============================================================================================== # # Microsoft PowerShell Source File -- Created with SAPIEN Technologies PrimalScript 2009 # # NAME: Tree.ps1 # v1.2 # Changed [int] to [int64] to handle large folder sizes # v1.1 # Fixed a problem where a directory with 1 file was showing as having 0 files # # # AUTHOR: Jeffery Hicks, PowerShell MVP , SAPIEN Technologies, Inc. # DATE : 4/3/2009 # # COMMENT: Display a PowerShell equivalent of the CMD TREE command, but with # additional information. # PS C:\scripts\> .\tree.ps1 -path c:\files # The default behavior is to display the tree as green text using Write-Host. If # you prefer to write to the pipeline so you can capture output, use the -pipeline parameter. # # PS C:\scripts\> .\tree.ps1 -path c:\files -pipeline | Out-File filetree.txt # DISCLAIMER AND WARNING: # THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY # KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. # TEST THOROUGHLY IN A NON-PRODUCTION ENVIRONMENT. IF YOU DON'T KNOW WHAT THIS # SCRIPT WILL DO...DO NOT RUN IT! # # ============================================================================================== #Tree.ps1 Param ([string]$path=$env:temp, [switch]$pipeline) Function Get-SubFolder { Param([int]$TabLevel=0,[string]$path) $TabLevel+=1 $subdirs = dir $path | where {$_.GetType() -match "directoryInfo"} if ($subdirs) { foreach ($subdir in $subdirs) { $subfiles=dir $subdir.fullname | where {$_.GetType() -match "FileInfo"} $stats=$subfiles | Measure-Object -sum length [int64]$subcount=$stats.count [int64]$subsize=$stats.sum $leaf=("{0}{1}{2}{3} ({4} files {5} KB)" -f ` (" "*$tabLevel),"|",("_"*$TabLevel),$subdir.name,$subcount,("{0:N2}" -f ($subsize/1KB))) if ($pipeline) { write $leaf } else { Write-Host $leaf -foregroundcolor green } Get-SubFolder $TabLevel $subdir.fullname } } $TabLevel-=1 } #Turn off the error pipeline $ErrorActionPreference="SilentlyContinue" if ((Get-Item $path).exists) { $data=dir $path $files=$data | where {$_.GetType() -match "FileInfo"} [int64]$count=$files.count [int64]$size=($files | Measure-Object -Sum Length).sum #write the tree root $leaf=("{0} ({1} files {2} KB)" -f $path,$count,("{0:N2}" -f ($size/1KB))) if ($pipeline) { write $leaf } else { Write-Host $leaf -foregroundcolor green } $TabLevel=0 #enumerate child folders Get-SubFolder -tablevel $tablevel -path $path } else { Write-Warning "Failed to find $path" }