function Sort-Size {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string] $Name
[Parameter(ValueFromPipeline = $true)]
$Path,
$Lenght
)
begin {
$Lenght = @()
}
process {
$Path = Get-ChildItem -recurse -File $Name
}
end {
$Path | Select-Object FullName, @{Name='FileSizeInKb';Expression={$_.Length/1KB}} | Sort-Object -Property FileSizeInKb | Format-Table -AutoSize
}
}
Sort-Size -Name {Test-Path -Name "C:\"}
This code only sorts in one folder, how to make it sort in different folders?
CodePudding user response:
For this you don't need parameters Name
and Length
.
Instead, I would add an optional file pattern to look for and add a switch whether or not you want the function to recurse through the various subfolders.
Also, I would not have it return the DISPLAY ONLY output of Format-Table
, but the sorted list of files itself. Then when caling the function you can decide if you want to pipe that to Format-* or do something else with the data.
Something like below:
function Sort-Size {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[ValidateScript({ $_ | Test-Path -PathType Container })]
[Alias('FullName')]
[string]$Path,
[string]$Pattern = '*.*',
[switch]$Recurse
)
Write-Verbose "Searching files in '$Path' with pattern '$Pattern'"
Get-ChildItem -Path $Path -File -Filter $Pattern -Recurse:$Recurse |
Select-Object Name, DirectoryName, @{Name='FileSizeInKb';Expression={[Math]::Round($_.Length/1KB, 2)}} |
Sort-Object FileSizeInKb
}
Sort-Size -Path "C:\Users\user" | Format-Table -Property Name,FileSizeInKb -AutoSize
CodePudding user response:
function Sort-Size {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline = $true)]
$Path,
$Lenght,
$Name
)
begin {
$Lenght = @()
}
process {
$Path = Get-ChildItem -recurse -File "$Name"
}
end {
$Path | Select-Object FullName, @{Name='FileSizeInKb';Expression={$_.Length/1KB}} | Sort-Object -Property FileSizeInKb | Format-Table -AutoSize
}
}
#Sort-Size -Path "C:\Users"
Sort-Size -Name "C:\Users\user"
#Get-Help "Sort-size"