added Get-FileSizes function

This commit is contained in:
2022-11-10 11:22:43 -05:00
parent 2f49d7d7e3
commit f0b6075940
+51
View File
@@ -672,5 +672,56 @@ function Stop-MemoryHog ([string]$AppName,[int]$MemoryLimit) {
}
}
# Returns a formatted list of the largest or smallest files in a directory
function Get-FileSizes {
param(
[Parameter(ValueFromPipeline=$true)][string]$Path,
[switch]$Recurse,
[switch]$IncludeHidden,
[Parameter(ParameterSetName="largest")][int]$Largest,
[Parameter(ParameterSetName="smallest")][int]$Smallest,
[string]$Units,
[int]$Precision=2
)
# If no path is specified, set $Path to the directory containing user profiles
If (-not $Path ) {
$Path = (Get-ItemPropertyValue -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList' -Name ProfilesDirectory)
$Recurse = $true
$IncludeHidden = $false
}
# Change the sort order depending on which parameter set was specified
Switch ( $PSCmdlet.ParameterSetName ) {
"largest" { $SortOrder = $true ; $Quantity = $Largest }
"smallest" { $SortOrder = $false ; $Quantity = $Smallest }
}
# Set the units to show sizes in output
Switch ( $Units.ToUpper() ) {
"KB" { $UnitLabel = "Kilobytes (KB)" ; $Divisor = 1KB }
"MB" { $UnitLabel = "Megabytes (MB)" ; $Divisor = 1MB }
"GB" { $UnitLabel = "Gigabytes (GB)" ; $Divisor = 1GB }
"TB" { $UnitLabel = "Terabytes (TB)" ; $Divisor = 1TB }
default { $UnitLabel = "Bytes" ; $Divisor = 1 }
}
# Get the file paths and sizes as specified
$FileSizes = Get-ChildItem $Path -Recurse:$Recurse -Force:$IncludeHidden -ErrorAction SilentlyContinue |
Sort-Object -Descending:$SortOrder -Property Length |
Select-Object -First $Quantity @{Name="File Path";Expression={$_.DirectoryName + '\' + $_.Name}}, @{Name=$UnitLabel;Expression={[Math]::Round($_.Length / $Divisor, $Precision)}}
# Set output prefix
$prefix = "The ${Quantity} " + $PSCmdlet.ParameterSetName + " files found at ""${Path}"""
# Output to console
$constr = "${prefix}" + $($FileSizes | Out-String)
Write-Output $constr
# Output to log file
$logstr = "${prefix}" + $($FileSizes | Format-List | Out-String)
LogMsg $logstr
}
Setup-MSPDirectories
Setup-LogFile