How to sort output based on a custom created object in Powershell?

60 Views Asked by At

I've the following function to get folder sizes, under a given directory.


function Get-FolderSize {
      [CmdletBinding()]
      param (
        [Parameter(ValueFromPipeline=$true)]
        [string]$Path
      )
      
      process {
        $folders = Get-ChildItem $Path -Directory
        foreach ($folder in $folders) {
          $size = [Math]::round((Get-ChildItem $folder.FullName -Recurse | Measure-Object -Property Length -Sum).Sum / 1GB, 2)
          $obj = New-Object PSObject -Property @{
            Name = $folder.Name
            Size = $size
          }
          $obj
        }
      }
    };
    $path =  pwd;
    Get-FolderSize -Path $path -ErrorAction SilentlyContinue;

The above code gives the following o/p:

Name                 Size
----                 ----
getting-started      0.01
Favorites               0
iotedge              0.04
git                  0.12
eclipse-workspace    0.16
Documents            0.09
Desktop                 0
eclipse              0.29
Downloads            1.66
Links                   0
source                  0
Searches                0
workspace            0.16

I need to sort the o/p, based on the custom-object 'Size'. Can someone help me out here? Thanks in advance.

2

There are 2 best solutions below

0
Ranadip Dutta On

Putting Abraham's comment to answer:

Sort-Object command does your job seamlessly

Replace

Get-FolderSize -Path $path -ErrorAction SilentlyContinue 

With This:

Get-FolderSize -Path $path -ErrorAction SilentlyContinue | Sort-Object Size -Descending
0
Civette On
Function Get-FolderSize {
  [CmdletBinding()]
  param (
    [Parameter(ValueFromPipeline=$true)]
    [string]$Path
  )

  process {
    $return= @()
    $folders = Get-ChildItem $Path -Directory
    foreach ($folder in $folders) {
      $size = [Math]::round((Get-ChildItem $folder.FullName -Recurse | Measure-Object -Property Length -Sum).Sum / 1GB, 2)
      $obj = New-Object PSObject -Property @{
        Name = $folder.Name
        Size = $size
      }
      $return += $obj
    }
    $return = $return | Sort-Object -Property Size -Descending
    return $return
  }
}

$path =  "my full path"
Get-FolderSize -Path $path -ErrorAction SilentlyContinue