Home > Software design >  How can i format correctly the "Size" param at Get-Partition?
How can i format correctly the "Size" param at Get-Partition?

Time:05-05

When i use get-partition i get something like that:

PartitionNumber                                   Size Type
---------------                                   ---- ----
1                                            931.51 GB IFS

As you can see, the Size is correctly formatted with GB behind.

When I use:

get-partition | select Size

         Size
         ----
    104857600

i get the size in the wrong format. is it possible to get it like the upper one without math functions?

CodePudding user response:

If you just want to print the sizes expressed in GB with two decimal places, with suffix GB, do the following:

Get-Partition | ForEach-Object { '{0:N2} GB' -f ($_.Size / 1gb) }

If you also want a column header, use Format-Table with a calculated property as follows:
Format-Table @{ Name='Size'; Expression={ '{0:N2} GB' -f ($_.Size / 1gb) } }. You could use the same technique with Select-Object, but since for-display formatting is the goal here, that isn't necessary.

If you want to auto-scale the sizes (using simulated input objects to demonstrate, via PowerShell's number-literal suffixes such as kb, which are multiples of 1024):

@{ Size = 42 }, 
@{ Size = 42.1kb }, 
@{ Size = 42.2mb }, 
@{ Size = 42.3gb }, 
@{ Size = 42.4tb },
@{ Size = 42.4pb } |
  ForEach-Object { 
    $decimalPlaces = 2
    $scaledSize = switch ($_.Size) {
      { $_ -ge 1pb } { $_ / 1pb; $suffix='PB'; break }
      { $_ -ge 1tb } { $_ / 1tb; $suffix='TB'; break }
      { $_ -ge 1gb } { $_ / 1gb; $suffix='GB'; break }
      { $_ -ge 1mb } { $_ / 1mb; $suffix='MB'; break }
      { $_ -ge 1kb } { $_ / 1kb; $suffix='KB'; break }
      default        { $_; $suffix='B'; $decimalPlaces = 0 }
    }

    "{0:N${decimalPlaces}} $suffix" -f $scaledSize
  }

Output:

42 B
42.10 KB
42.20 MB
42.30 GB
42.40 TB
42.40 PB

Note: The auto-scaling code above is essentially a more readable formulation of what PowerShell does in its default for-display formatting for the output objects emitted by Get-Partition, via their Microsoft.Management.Infrastructure.CimInstance#MSFT_Partition ETS type name; specifically, the code used is:

$size = $_.Size;
$postfixes = @( "B", "KB", "MB", "GB", "TB", "PB" )
for ($i=0; $size -ge 1024 -and $i -lt $postfixes.Length; $i  ) { $size = $size / 1024; }
return ""   [System.Math]::Round($size,2)   " "   $postfixes[$i];

CodePudding user response:

Is using math to round the number ok?

Get-Partition | Select DriveLetter, PartitionNumber, @{Label = "Size"; Expression = { [math]::round($_.Size / 1gb, 2) } }
  • Related