Converting data to KB, MB, GB

I have been trying to convert raw numbers in a file to KB, GB or MB. For ex

get-content c:\temp\numbers.txt | select -object Name, {$_.Somename.value.ToMB()}

the text file contain numbers of different sizes that were recorded from another sheet.

or I would really like to pipe it into something like this

  $_ | Select-Object Name, @{n='Count';e={ $Count }}, @{n='Size';e={
    If     ($Size -gt 1GB) { "$('{0:N2}' -f ($Size / 1Gb)) GB" }
    ElseIf ($Size -gt 1MB) { "$('{0:N2}' -f ($Size / 1Mb)) MB" }
    ElseIf ($Size -gt 1KB) { "$('{0:N2}' -f ($Size / 1Kb)) KB" }
    Else                   { "$Size b" } }}
Who is Participating?
Chris DentPowerShell DeveloperCommented:
It's not quite as complex as the two snippets you have.
Get-Content c:\temp\numbers.txt | ForEach-Object {
  If ($_ -gt 1GB) { 
    "$('{0:N2}' -f ($_ / 1Gb)) GB" 
  } ElseIf ($_ -gt 1Mb) {
    "$('{0:N2}' -f ($_ / 1Mb)) MB"
  } ElseIf ($_ -gt 1Kb) {
    "$('{0:N2}' -f ($_ / 1Kb)) KB"
  } Else {
    "$_ b"

Open in new window

Is that what you had in mind?

techdriveAuthor Commented:
The logic is nice however I am getting the following below when I run this

Cannot compare "@{Name=439150512}" to "1073741824" because the objects are not the same type or the object "@{Name=439150512}" does not implement "IComparable".
At C:\temp\convert.ps1:2 char:13
+   If ($_ -gt <<<<  1GB) {
    + CategoryInfo          : NotSpecified: (:) [], ExtendedTypeSystemException
    + FullyQualifiedErrorId : PSObjectCompareTo
Chris DentPowerShell DeveloperCommented:
What exactly do you have in that text file of yours?

techdriveAuthor Commented:
Chris sorry the machine I was using is locked down. This worked perfectly thanks again.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.